@vultro/docstore-mysql 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,7 @@
1
+ /**
2
+ * MySQL 驱动入口。
3
+ *
4
+ * 驱动依赖安装在 `@vultro/docstore-mysql` 内,运行时包 / 测试不直接声明
5
+ * `mysql2`。这样只有真正选择 MySQL 文档存储的项目才会引入驱动。
6
+ */
7
+ export { default } from "mysql2/promise";
package/dist/driver.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from "mysql2/promise";
@@ -0,0 +1,7 @@
1
+ import { type DocStoreBackend } from "@vultro/core/docstore";
2
+ /**
3
+ * MySQL / TiDB 文档存储选择器(纯配置)。
4
+ *
5
+ * 实现由 `@vultro/docstore-mysql/runtime` 注册。
6
+ */
7
+ export declare function mysqlStore(): DocStoreBackend;
package/dist/index.js ADDED
@@ -0,0 +1,29 @@
1
+ import { resolveDocStoreCreator, resolveDocStoreDatabaseCreator } from "@vultro/core/docstore";
2
+ // src/index.ts
3
+ /**
4
+ * MySQL / TiDB 文档存储选择器(纯配置)。
5
+ *
6
+ * 实现由 `@vultro/docstore-mysql/runtime` 注册。
7
+ */
8
+ function mysqlStore() {
9
+ return {
10
+ name: "mysql",
11
+ runtimes: [
12
+ "cloudflare",
13
+ "cloud",
14
+ "bun",
15
+ "node"
16
+ ],
17
+ module: "@vultro/docstore-mysql",
18
+ exportName: "mysqlStore",
19
+ create(runtime, context) {
20
+ return resolveDocStoreCreator("mysql")(runtime, context);
21
+ },
22
+ createDatabase(runtime, context) {
23
+ const create = resolveDocStoreDatabaseCreator("mysql");
24
+ if (!create) throw new Error("mysql docstore database adapter is not registered");
25
+ return create(runtime, context);
26
+ }
27
+ };
28
+ }
29
+ export { mysqlStore };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * ============================================================================
3
+ * MySQL 文档存储适配器
4
+ * ============================================================================
5
+ *
6
+ * MySQL 与 SQLite / Postgres 的方言差异:
7
+ *
8
+ * - 占位符仍然是 `?`,不需要改写;
9
+ * - `INTEGER PRIMARY KEY AUTOINCREMENT` → `BIGINT AUTO_INCREMENT PRIMARY KEY`;
10
+ * - `REAL` → `DOUBLE`;
11
+ * - `INSERT OR REPLACE` → `REPLACE INTO`;
12
+ * - `INSERT OR IGNORE` → `INSERT IGNORE`;
13
+ * - `INSERT ... ON CONFLICT ... DO UPDATE` → `REPLACE INTO`(D1Cached 的
14
+ * upsert 都带完整行数据,因此整行替换语义等价);
15
+ * - `CREATE INDEX IF NOT EXISTS` 在 MySQL 上不通用,去掉 `IF NOT EXISTS`
16
+ * 并容忍重复索引错误;
17
+ * - `PRAGMA table_info(t)` → information_schema 查询;
18
+ * - `key` 是 MySQL 保留字,做列名时要加反引号;
19
+ * - TEXT 列不能直接做索引键或带 DEFAULT 值,建表 / 建索引时补前缀长度或
20
+ * 降级成 VARCHAR(见 `fixMysqlTextKeys`)。
21
+ */
22
+ import type { D1DatabaseLike, D1PreparedStatementLike } from "@vultro/core/d1";
23
+ import { AsyncCachedDocumentStore } from "@vultro/core";
24
+ import type { SchemaInfo } from "@vultro/core/schema-info";
25
+ /** MySQL client 最小接口;兼容 mysql2/promise 的 tuple 返回。 */
26
+ export interface MysqlClientLike {
27
+ query<T = Record<string, unknown>>(text: string, values?: unknown[]): Promise<{
28
+ rows?: T[];
29
+ affectedRows?: number;
30
+ insertId?: number;
31
+ }> | Promise<[T[], unknown]>;
32
+ transaction?<T>(callback: (client: MysqlClientLike) => Promise<T>): Promise<T>;
33
+ }
34
+ /** 把 SQLite 风格 SQL 转成 MySQL 可执行 SQL。 */
35
+ export declare function translateMysqlSql(text: string): string;
36
+ /** 把 MySQL client 包装成 D1DatabaseLike,供 AsyncCachedDocumentStore 复用。 */
37
+ export declare class MysqlD1Database implements D1DatabaseLike {
38
+ private readonly client;
39
+ /** 建表时记录 TEXT 列,供后续 CREATE INDEX 补前缀长度。 */
40
+ private readonly textColumnsByTable;
41
+ constructor(client: MysqlClientLike);
42
+ prepare(sql: string): D1PreparedStatementLike;
43
+ query<T>(sql: string, params: unknown[]): Promise<{
44
+ rows: T[];
45
+ affectedRows?: number;
46
+ insertId?: number;
47
+ }>;
48
+ execute(sql: string, params: unknown[]): Promise<void>;
49
+ batch(statements: D1PreparedStatementLike[]): Promise<unknown>;
50
+ }
51
+ /** 创建 MySQL 文档存储。 */
52
+ export declare function createMysqlDocumentStore(schema: SchemaInfo, client: MysqlClientLike): AsyncCachedDocumentStore;
package/dist/mysql.js ADDED
@@ -0,0 +1,197 @@
1
+ import { AsyncCachedDocumentStore } from "@vultro/core";
2
+ // src/mysql.ts
3
+ /**
4
+ * `key` 在 MySQL / TiDB 中是保留字,但 core 的 DDL 用它做列名。
5
+ *
6
+ * 只给「不在字符串或反引号里、且不是 PRIMARY/UNIQUE KEY 约束关键字」的
7
+ * `key` 加反引号;否则会把约束语法或字符串字面量改坏。
8
+ */
9
+ function quoteMysqlKey(sql) {
10
+ let result = "";
11
+ let inString = false;
12
+ let inBacktick = false;
13
+ for (let i = 0; i < sql.length; i++) {
14
+ const char = sql[i];
15
+ if (inBacktick) {
16
+ result += char;
17
+ if (char === "`") inBacktick = false;
18
+ continue;
19
+ }
20
+ if (char === "`") {
21
+ inBacktick = true;
22
+ result += char;
23
+ continue;
24
+ }
25
+ if (char === "'") {
26
+ if (inString && sql[i + 1] === "'") {
27
+ result += "''";
28
+ i++;
29
+ continue;
30
+ }
31
+ inString = !inString;
32
+ result += char;
33
+ continue;
34
+ }
35
+ if (!inString && /[A-Za-z_]/.test(char) && (i === 0 || !/[A-Za-z0-9_]/.test(sql[i - 1]))) {
36
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(sql.slice(i))[0];
37
+ const previousWord = result.trimEnd().split(/\s+/).at(-1)?.toLowerCase();
38
+ const isConstraintKeyword = word.toLowerCase() === "key" && (previousWord === "primary" || previousWord === "unique" || previousWord === "foreign");
39
+ result += word.toLowerCase() === "key" && !isConstraintKeyword ? "`key`" : word;
40
+ i += word.length - 1;
41
+ continue;
42
+ }
43
+ result += char;
44
+ }
45
+ return result;
46
+ }
47
+ /** 把 SQLite 风格 SQL 转成 MySQL 可执行 SQL。 */
48
+ function translateMysqlSql(text) {
49
+ const pragma = /^\s*PRAGMA\s+table_info\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)\s*;?\s*$/i.exec(text);
50
+ if (pragma) return `SELECT column_name AS name FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = '${pragma[1]}'`;
51
+ let sql = text.replace(/"window"/g, "`window`").replace(/INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT/gi, "BIGINT AUTO_INCREMENT PRIMARY KEY").replace(/\bINTEGER\b/g, "BIGINT").replace(/\bREAL\b/g, "DOUBLE").replace(/CREATE\s+INDEX\s+IF\s+NOT\s+EXISTS/gi, "CREATE INDEX");
52
+ sql = sql.replace(/\bINSERT\s+INTO\b([\s\S]*?)\s+ON\s+CONFLICT\s*\([^)]*\)\s+DO\s+UPDATE\s+SET[\s\S]*$/i, "REPLACE INTO$1");
53
+ sql = sql.replace(/^\s*INSERT\s+OR\s+REPLACE\s+INTO/i, "REPLACE INTO");
54
+ sql = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO/i, "INSERT IGNORE INTO");
55
+ return quoteMysqlKey(sql);
56
+ }
57
+ /**
58
+ * MySQL 不允许 BLOB/TEXT 列直接做索引键,必须指定前缀长度。
59
+ *
60
+ * core 的 DDL 在 SQLite / Postgres 上统一用 TEXT 存 id / name / token 等短
61
+ * 字符串,这里在 DDL 层补上前缀长度,避免为 MySQL 单独维护一套表结构。
62
+ * 191 是 utf8mb4 下单列 764 字节的经验值,四列复合主键仍不会触及
63
+ * InnoDB 的 3072 字节上限;Vultro 的 id 都是短 ID,前缀足够区分。
64
+ */
65
+ var MYSQL_TEXT_KEY_PREFIX = 191;
66
+ /** 给主键 / 索引列清单中的 TEXT 列补前缀长度。 */
67
+ function addTextKeyPrefixes(columns, textColumns) {
68
+ return columns.split(",").map((part) => {
69
+ const trimmed = part.trim();
70
+ const name = trimmed.split(/\s+/)[0]?.replace(/`/g, "").toLowerCase();
71
+ if (name && textColumns.has(name)) return `${trimmed}(${MYSQL_TEXT_KEY_PREFIX})`;
72
+ return trimmed;
73
+ }).join(", ");
74
+ }
75
+ /**
76
+ * 修正 DDL 里的 TEXT 键列,让同一份 core DDL 能在 MySQL / TiDB 上执行。
77
+ *
78
+ * - `CREATE TABLE`:记录 TEXT 列;行内 `TEXT PRIMARY KEY` 改成
79
+ * `VARCHAR(191) PRIMARY KEY`,表级主键里的 TEXT 列补前缀长度;
80
+ * - `CREATE INDEX`:根据已记录的表结构给 TEXT 列补前缀长度。
81
+ *
82
+ * 状态按 `MysqlD1Database` 实例保存;D1Cached 先建表再建索引,顺序是确定的。
83
+ */
84
+ function fixMysqlTextKeys(sql, textColumnsByTable) {
85
+ const createTable = /^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?(\w+)`?\s*\(([\s\S]*)\)\s*;?\s*$/i.exec(sql);
86
+ if (createTable) {
87
+ const table = createTable[1].toLowerCase();
88
+ const body = createTable[2];
89
+ const textColumns = /* @__PURE__ */ new Set();
90
+ for (const match of body.matchAll(/^\s*`?(\w+)`?\s+TEXT\b/gim)) textColumns.add(match[1].toLowerCase());
91
+ textColumnsByTable.set(table, textColumns);
92
+ let fixedBody = body.replace(/(`?\w+`?\s+)TEXT(\s+(?:NOT\s+NULL\s+)?PRIMARY\s+KEY\b)/gi, `$1VARCHAR(${MYSQL_TEXT_KEY_PREFIX})$2`);
93
+ fixedBody = fixedBody.replace(/(`?\w+`?\s+)TEXT(\s+NOT\s+NULL\s+)?(DEFAULT\s+)/gi, `$1VARCHAR(${MYSQL_TEXT_KEY_PREFIX})$2$3`);
94
+ fixedBody = fixedBody.replace(/PRIMARY\s+KEY\s*\(([^)]*)\)/gi, (_match, list) => `PRIMARY KEY (${addTextKeyPrefixes(list, textColumns)})`);
95
+ return sql.replace(body, fixedBody);
96
+ }
97
+ const createIndex = /^(\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+\S+\s+ON\s+`?(\w+)`?\s*)\(([^)]*)\)([\s\S]*)$/i.exec(sql);
98
+ if (createIndex) {
99
+ const textColumns = textColumnsByTable.get(createIndex[2].toLowerCase());
100
+ if (textColumns?.size) return `${createIndex[1]}(${addTextKeyPrefixes(createIndex[3], textColumns)})${createIndex[4]}`;
101
+ }
102
+ return sql;
103
+ }
104
+ function isDuplicateIndexError(error) {
105
+ const value = error;
106
+ return value?.code === "ER_DUP_KEYNAME" || value?.errno === 1061 || /Duplicate key name/i.test(value?.message ?? "");
107
+ }
108
+ function normalizeResult(result) {
109
+ if (Array.isArray(result) && Array.isArray(result[0])) return { rows: result[0] };
110
+ const value = result;
111
+ return {
112
+ rows: value?.rows ?? [],
113
+ affectedRows: value?.affectedRows,
114
+ insertId: value?.insertId
115
+ };
116
+ }
117
+ var MysqlPreparedStatement = class MysqlPreparedStatement {
118
+ database;
119
+ sql;
120
+ params;
121
+ constructor(database, sql, params = []) {
122
+ this.database = database;
123
+ this.sql = sql;
124
+ this.params = params;
125
+ }
126
+ bind(...values) {
127
+ return new MysqlPreparedStatement(this.database, this.sql, values);
128
+ }
129
+ async first() {
130
+ return (await this.database.query(this.sql, this.params)).rows[0] ?? null;
131
+ }
132
+ async all() {
133
+ return { results: (await this.database.query(this.sql, this.params)).rows };
134
+ }
135
+ async run() {
136
+ await this.database.execute(this.sql, this.params);
137
+ return { success: true };
138
+ }
139
+ raw() {
140
+ return {
141
+ sql: this.sql,
142
+ params: this.params
143
+ };
144
+ }
145
+ };
146
+ /** 把 MySQL client 包装成 D1DatabaseLike,供 AsyncCachedDocumentStore 复用。 */
147
+ var MysqlD1Database = class {
148
+ client;
149
+ /** 建表时记录 TEXT 列,供后续 CREATE INDEX 补前缀长度。 */
150
+ textColumnsByTable = /* @__PURE__ */ new Map();
151
+ constructor(client) {
152
+ this.client = client;
153
+ }
154
+ prepare(sql) {
155
+ const translated = fixMysqlTextKeys(translateMysqlSql(sql), this.textColumnsByTable);
156
+ return new MysqlPreparedStatement(this, translated);
157
+ }
158
+ async query(sql, params) {
159
+ return normalizeResult(await this.client.query(sql, params));
160
+ }
161
+ async execute(sql, params) {
162
+ try {
163
+ await this.client.query(sql, params);
164
+ } catch (error) {
165
+ if (/^\s*CREATE\s+INDEX/i.test(sql) && isDuplicateIndexError(error)) return;
166
+ throw error;
167
+ }
168
+ }
169
+ async batch(statements) {
170
+ const run = async (client) => {
171
+ for (const statement of statements) {
172
+ const { sql, params } = statement.raw();
173
+ try {
174
+ await client.query(sql, params);
175
+ } catch (error) {
176
+ if (/^\s*CREATE\s+INDEX/i.test(sql) && isDuplicateIndexError(error)) continue;
177
+ throw error;
178
+ }
179
+ }
180
+ };
181
+ if (this.client.transaction) return this.client.transaction(run);
182
+ await this.client.query("START TRANSACTION");
183
+ try {
184
+ await run(this.client);
185
+ await this.client.query("COMMIT");
186
+ } catch (error) {
187
+ await this.client.query("ROLLBACK");
188
+ throw error;
189
+ }
190
+ return { success: true };
191
+ }
192
+ };
193
+ /** 创建 MySQL 文档存储。 */
194
+ function createMysqlDocumentStore(schema, client) {
195
+ return new AsyncCachedDocumentStore(schema, new MysqlD1Database(client));
196
+ }
197
+ export { MysqlD1Database, createMysqlDocumentStore, translateMysqlSql };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import { registerDocStore, registerDocStoreDatabase } from "@vultro/core/docstore";
2
+ import { MysqlD1Database, createMysqlDocumentStore } from "./mysql.js";
3
+ // src/runtime.ts
4
+ /** MySQL / TiDB 文档存储实现。 */
5
+ registerDocStore("mysql", (_runtime, context) => {
6
+ if (!context.mysql) throw new Error("mysqlStore requires a MySQL client");
7
+ return createMysqlDocumentStore(context.schema, context.mysql);
8
+ });
9
+ /** MySQL client → D1DatabaseLike,供运行时内部服务复用。 */
10
+ registerDocStoreDatabase("mysql", (_runtime, context) => {
11
+ if (!context.mysql) throw new Error("mysqlStore requires a MySQL client");
12
+ return new MysqlD1Database(context.mysql);
13
+ });
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@vultro/docstore-mysql",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "description": "MySQL document store backend for Vultro",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./driver": {
13
+ "types": "./dist/driver.d.ts",
14
+ "import": "./dist/driver.js",
15
+ "default": "./dist/driver.js"
16
+ },
17
+ "./mysql": {
18
+ "types": "./dist/mysql.d.ts",
19
+ "import": "./dist/mysql.js",
20
+ "default": "./dist/mysql.js"
21
+ },
22
+ "./runtime": {
23
+ "types": "./dist/runtime.d.ts",
24
+ "import": "./dist/runtime.js",
25
+ "default": "./dist/runtime.js"
26
+ }
27
+ },
28
+ "dependencies": {
29
+ "@vultro/core": "0.0.1",
30
+ "mysql2": "^3.26.1"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "types": "./dist/index.d.ts"
36
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.