@dyrected/db-mysql 0.0.0-pr-18-20260828214838
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/LICENSE.md +50 -0
- package/README.md +3 -0
- package/dist/index.cjs +465 -0
- package/dist/index.d.cts +70 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.js +429 -0
- package/package.json +40 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Business Source License 1.1
|
|
2
|
+
|
|
3
|
+
Parameters
|
|
4
|
+
|
|
5
|
+
Licensor: Dyrected
|
|
6
|
+
Licensed Work: Dyrected
|
|
7
|
+
Additional Use Grant: Production use and commercial use of the Licensed Work are permitted for your own internal business operations, your own websites and applications, and client websites or applications that you build or deploy on behalf of a client, provided that you do not, without a separate commercial license from the Licensor, (a) provide the Licensed Work as a hosted or managed service to third parties, (b) embed, white-label, sublicense, or otherwise redistribute the Licensed Work as part of a multi-tenant or customer-facing SaaS, platform, or developer service, or (c) enable third parties to create, manage, or operate independent projects, sites, workspaces, or environments using the Licensed Work as a material part of the service you provide.
|
|
8
|
+
Change Date: 2030-05-18
|
|
9
|
+
Change License: Apache License 2.0
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
Business Source License 1.1
|
|
14
|
+
|
|
15
|
+
License text copyright © 2024 MariaDB plc, All Rights Reserved.
|
|
16
|
+
“Business Source License” is a trademark of MariaDB plc.
|
|
17
|
+
|
|
18
|
+
### Terms
|
|
19
|
+
|
|
20
|
+
The Licensor hereby grants you the right to copy, modify, create derivative works, redistribute, and make non-production use of the Licensed Work. The Licensor may make an Additional Use Grant, above, permitting limited production use.
|
|
21
|
+
|
|
22
|
+
Effective on the Change Date, or the fourth anniversary of the first publicly available distribution of a specific version of the Licensed Work under this License, whichever comes first, the Licensor hereby grants you rights under the terms of the Change License, and the rights granted in the paragraph above terminate.
|
|
23
|
+
|
|
24
|
+
If your use of the Licensed Work does not comply with the requirements currently in effect as described in this License, you must purchase a commercial license from the Licensor, its affiliated entities, or authorized resellers, or you must refrain from using the Licensed Work.
|
|
25
|
+
|
|
26
|
+
All copies of the original and modified Licensed Work, and derivative works of the Licensed Work, are subject to this License. This License applies separately for each version of the Licensed Work and the Change Date may vary for each version of the Licensed Work released by Licensor.
|
|
27
|
+
|
|
28
|
+
You must conspicuously display this License on each original or modified copy of the Licensed Work. If you receive the Licensed Work in original or modified form from a third party, the terms and conditions set forth in this License apply to your use of that work.
|
|
29
|
+
|
|
30
|
+
Any use of the Licensed Work in violation of this License will automatically terminate your rights under this License for the current and all other versions of the Licensed Work.
|
|
31
|
+
|
|
32
|
+
This License does not grant you any right in any trademark or logo of Licensor or its affiliates (provided that you may use a trademark or logo of Licensor as expressly required by this License).
|
|
33
|
+
|
|
34
|
+
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE.
|
|
35
|
+
|
|
36
|
+
MariaDB hereby grants you permission to use this License’s text to license your works, and to refer to it using the trademark “Business Source License”, as long as you comply with the Covenants of Licensor below.
|
|
37
|
+
|
|
38
|
+
### Covenants of Licensor
|
|
39
|
+
|
|
40
|
+
In consideration of the right to use this License’s text and the “Business Source License” name and trademark, Licensor covenants to MariaDB, and to all other recipients of the licensed work to be provided by Licensor:
|
|
41
|
+
|
|
42
|
+
1. To specify as the Change License the GPL Version 2.0 or any later version, or a license that is compatible with GPL Version 2.0 or a later version, where “compatible” means that software provided under the Change License can be included in a program with software provided under GPL Version 2.0 or a later version. Licensor may specify additional Change Licenses without limitation.
|
|
43
|
+
|
|
44
|
+
2. To either: (a) specify an additional grant of rights to use that does not impose any additional restriction on the right granted in this License, as the Additional Use Grant; or (b) insert the text “None”.
|
|
45
|
+
|
|
46
|
+
3. Not to modify this License in any other way.
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
The Business Source License (this document, or the “License”) is not an Open Source license. However, the Licensed Work will eventually be made available under an Open Source License, as stated in this License.
|
package/README.md
ADDED
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
MysqlAdapter: () => MysqlAdapter,
|
|
34
|
+
mysqlAdapter: () => mysqlAdapter
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(index_exports);
|
|
37
|
+
var import_core = require("@dyrected/core");
|
|
38
|
+
var import_promise = __toESM(require("mysql2/promise"), 1);
|
|
39
|
+
function escapeMysqlIdentifier(identifier) {
|
|
40
|
+
return `\`${identifier.replace(/`/g, "``")}\``;
|
|
41
|
+
}
|
|
42
|
+
function normalizeMysqlSort(sort, existingCols) {
|
|
43
|
+
return (0, import_core.parseSort)(sort).map(({ field, direction }) => {
|
|
44
|
+
if (field === "createdAt" || field === "created_at") return `\`created_at\` ${direction}`;
|
|
45
|
+
if (field === "updatedAt" || field === "updated_at") return `\`updated_at\` ${direction}`;
|
|
46
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
47
|
+
return `${escapeMysqlIdentifier(field)} ${direction}`;
|
|
48
|
+
}
|
|
49
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}')) ${direction}`;
|
|
50
|
+
}).join(", ");
|
|
51
|
+
}
|
|
52
|
+
var MysqlAdapter = class {
|
|
53
|
+
pool;
|
|
54
|
+
config;
|
|
55
|
+
initPromise = null;
|
|
56
|
+
inTransaction = false;
|
|
57
|
+
constructor(config) {
|
|
58
|
+
this.config = config;
|
|
59
|
+
}
|
|
60
|
+
handleConnectionError(err) {
|
|
61
|
+
if (err && (err.code === "EADDRNOTAVAIL" || err.message?.includes("EADDRNOTAVAIL"))) {
|
|
62
|
+
const customMessage = `
|
|
63
|
+
[dyrected/db-mysql] ERROR: MySQL connection failed with EADDRNOTAVAIL.
|
|
64
|
+
--------------------------------------------------------------------------------
|
|
65
|
+
This error often occurs when:
|
|
66
|
+
1. 'localhost' is resolved to an IPv6 address (::1) but MySQL is only listening on IPv4 (127.0.0.1).
|
|
67
|
+
2. The MySQL server is not running or is bound to a different port.
|
|
68
|
+
|
|
69
|
+
FIX INSTRUCTIONS:
|
|
70
|
+
- Try changing your host configuration in '.env' or config from 'localhost' to '127.0.0.1'.
|
|
71
|
+
- Make sure your local MySQL service is active and running on the configured port.
|
|
72
|
+
--------------------------------------------------------------------------------
|
|
73
|
+
`;
|
|
74
|
+
console.error(customMessage);
|
|
75
|
+
throw new Error(`MySQL Connection Failed: EADDRNOTAVAIL. Hint: Try using '127.0.0.1' instead of 'localhost'. Original: ${err.message}`);
|
|
76
|
+
}
|
|
77
|
+
throw err;
|
|
78
|
+
}
|
|
79
|
+
async ensureInitialized() {
|
|
80
|
+
if (!this.initPromise) {
|
|
81
|
+
this.initPromise = this.initialize();
|
|
82
|
+
}
|
|
83
|
+
await this.initPromise;
|
|
84
|
+
}
|
|
85
|
+
async initialize() {
|
|
86
|
+
const config = this.config;
|
|
87
|
+
let dbName = config.database;
|
|
88
|
+
let serverConfig = null;
|
|
89
|
+
if (config.url) {
|
|
90
|
+
try {
|
|
91
|
+
const parsed = new URL(config.url);
|
|
92
|
+
dbName = parsed.pathname.replace(/^\//, "");
|
|
93
|
+
const serverUrl = `${parsed.protocol}//${parsed.username}:${parsed.password}@${parsed.host}`;
|
|
94
|
+
serverConfig = serverUrl;
|
|
95
|
+
} catch (err) {
|
|
96
|
+
}
|
|
97
|
+
} else {
|
|
98
|
+
serverConfig = {
|
|
99
|
+
host: config.host ?? "localhost",
|
|
100
|
+
port: config.port ?? 3306,
|
|
101
|
+
user: config.user,
|
|
102
|
+
password: config.password
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
if (dbName && serverConfig) {
|
|
106
|
+
try {
|
|
107
|
+
const tempConn = await import_promise.default.createConnection(serverConfig);
|
|
108
|
+
await tempConn.query(`CREATE DATABASE IF NOT EXISTS \`${dbName}\``);
|
|
109
|
+
await tempConn.end();
|
|
110
|
+
console.log(`[dyrected/db-mysql] Database "${dbName}" checked/created successfully`);
|
|
111
|
+
} catch (err) {
|
|
112
|
+
console.warn(`[dyrected/db-mysql] Auto-creation of database "${dbName}" skipped/failed:`, err.message);
|
|
113
|
+
if (err.code === "EADDRNOTAVAIL" || err.message?.includes("EADDRNOTAVAIL")) {
|
|
114
|
+
this.handleConnectionError(err);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (config.url) {
|
|
119
|
+
this.pool = import_promise.default.createPool(config.url);
|
|
120
|
+
} else {
|
|
121
|
+
this.pool = import_promise.default.createPool({
|
|
122
|
+
host: config.host ?? "localhost",
|
|
123
|
+
port: config.port ?? 3306,
|
|
124
|
+
user: config.user,
|
|
125
|
+
password: config.password,
|
|
126
|
+
database: config.database,
|
|
127
|
+
dateStrings: true
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
await this.pool.query(`
|
|
132
|
+
CREATE TABLE IF NOT EXISTS dyrected_internal (
|
|
133
|
+
\`key\` VARCHAR(255) PRIMARY KEY,
|
|
134
|
+
value JSON NOT NULL
|
|
135
|
+
)
|
|
136
|
+
`);
|
|
137
|
+
} catch (err) {
|
|
138
|
+
this.handleConnectionError(err);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async query(sql, params) {
|
|
142
|
+
await this.ensureInitialized();
|
|
143
|
+
try {
|
|
144
|
+
return await this.pool.query(sql, params);
|
|
145
|
+
} catch (err) {
|
|
146
|
+
this.handleConnectionError(err);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async execute(sql, params) {
|
|
150
|
+
await this.ensureInitialized();
|
|
151
|
+
try {
|
|
152
|
+
return await this.pool.execute(sql, params);
|
|
153
|
+
} catch (err) {
|
|
154
|
+
this.handleConnectionError(err);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
getTableName(slug) {
|
|
158
|
+
return `collection_${slug}`;
|
|
159
|
+
}
|
|
160
|
+
async ensureTable(slug, fields = []) {
|
|
161
|
+
const tableName = this.getTableName(slug);
|
|
162
|
+
await this.query(`
|
|
163
|
+
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
|
|
164
|
+
id VARCHAR(36) PRIMARY KEY,
|
|
165
|
+
data JSON NOT NULL,
|
|
166
|
+
created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3),
|
|
167
|
+
updated_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
|
168
|
+
)
|
|
169
|
+
`);
|
|
170
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
171
|
+
const existingCols = cols.map((c) => c.Field);
|
|
172
|
+
for (const field of fields) {
|
|
173
|
+
if (field.promoted && !existingCols.includes(field.name)) {
|
|
174
|
+
console.log(`[dyrected/mysql] Promoting field "${field.name}" to column in ${tableName}`);
|
|
175
|
+
let sqlType = "TEXT";
|
|
176
|
+
if (field.type === "number") sqlType = "DECIMAL(19,4)";
|
|
177
|
+
if (field.type === "boolean") sqlType = "TINYINT(1)";
|
|
178
|
+
await this.query(`ALTER TABLE \`${tableName}\` ADD COLUMN \`${field.name}\` ${sqlType}`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async find(args) {
|
|
183
|
+
if (!this.inTransaction) await this.ensureTable(args.collection);
|
|
184
|
+
const tableName = this.getTableName(args.collection);
|
|
185
|
+
const limit = args.limit ?? 10;
|
|
186
|
+
const page = args.page ?? 1;
|
|
187
|
+
const offset = (page - 1) * limit;
|
|
188
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
189
|
+
const existingCols = cols.map((c) => c.Field);
|
|
190
|
+
let whereSql = "";
|
|
191
|
+
let whereParams = [];
|
|
192
|
+
if (args.where && Object.keys(args.where).length > 0) {
|
|
193
|
+
const result = (0, import_core.parseSqlWhere)(
|
|
194
|
+
args.where,
|
|
195
|
+
(field) => {
|
|
196
|
+
if (field === "createdAt") return "`created_at`";
|
|
197
|
+
if (field === "updatedAt") return "`updated_at`";
|
|
198
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
199
|
+
return `\`${field}\``;
|
|
200
|
+
}
|
|
201
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}'))`;
|
|
202
|
+
},
|
|
203
|
+
"?"
|
|
204
|
+
);
|
|
205
|
+
whereSql = `WHERE ${result.sql}`;
|
|
206
|
+
whereParams = result.params;
|
|
207
|
+
}
|
|
208
|
+
const sort = normalizeMysqlSort(args.sort, existingCols);
|
|
209
|
+
const [countRows] = await this.query(
|
|
210
|
+
`SELECT COUNT(*) AS total FROM \`${tableName}\` ${whereSql}`,
|
|
211
|
+
whereParams
|
|
212
|
+
);
|
|
213
|
+
const total = Number(countRows[0].total);
|
|
214
|
+
const [rows] = await this.query(
|
|
215
|
+
`SELECT * FROM \`${tableName}\` ${whereSql} ORDER BY ${sort} LIMIT ? OFFSET ?`,
|
|
216
|
+
[...whereParams, limit, offset]
|
|
217
|
+
);
|
|
218
|
+
const docs = rows.map((r) => ({
|
|
219
|
+
id: r.id,
|
|
220
|
+
...JSON.parse(typeof r.data === "string" ? r.data : JSON.stringify(r.data)),
|
|
221
|
+
createdAt: r.created_at,
|
|
222
|
+
updatedAt: r.updated_at
|
|
223
|
+
}));
|
|
224
|
+
const totalPages = Math.ceil(total / limit);
|
|
225
|
+
return {
|
|
226
|
+
docs,
|
|
227
|
+
total,
|
|
228
|
+
limit,
|
|
229
|
+
page,
|
|
230
|
+
totalPages,
|
|
231
|
+
hasNextPage: page < totalPages,
|
|
232
|
+
hasPrevPage: page > 1
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
async findOne(params) {
|
|
236
|
+
if (!this.inTransaction) await this.ensureTable(params.collection);
|
|
237
|
+
const tableName = this.getTableName(params.collection);
|
|
238
|
+
const lock = this.inTransaction ? " FOR UPDATE" : "";
|
|
239
|
+
const [rows] = await this.query(`SELECT * FROM \`${tableName}\` WHERE id = ?${lock}`, [params.id]);
|
|
240
|
+
const row = rows[0];
|
|
241
|
+
if (!row) return null;
|
|
242
|
+
return {
|
|
243
|
+
id: row.id,
|
|
244
|
+
...JSON.parse(typeof row.data === "string" ? row.data : JSON.stringify(row.data)),
|
|
245
|
+
createdAt: row.created_at,
|
|
246
|
+
updatedAt: row.updated_at
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
async create(params) {
|
|
250
|
+
if (!this.inTransaction) await this.ensureTable(params.collection);
|
|
251
|
+
const tableName = this.getTableName(params.collection);
|
|
252
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
253
|
+
const existingCols = cols.map((c) => c.Field);
|
|
254
|
+
const id = params.data.id ?? Math.random().toString(36).substring(7);
|
|
255
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
256
|
+
const data = { ...params.data };
|
|
257
|
+
delete data.id;
|
|
258
|
+
delete data.createdAt;
|
|
259
|
+
delete data.updatedAt;
|
|
260
|
+
const promotedValues = {};
|
|
261
|
+
for (const col of existingCols) {
|
|
262
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
263
|
+
if (data[col] !== void 0) {
|
|
264
|
+
promotedValues[col] = data[col];
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const colNames = ["id", "data", "created_at", "updated_at", ...Object.keys(promotedValues).map((k) => `\`${k}\``)];
|
|
268
|
+
const placeholders = colNames.map(() => "?").join(", ");
|
|
269
|
+
const values = [id, JSON.stringify(data), now, now, ...Object.values(promotedValues)];
|
|
270
|
+
await this.query(`INSERT INTO \`${tableName}\` (${colNames.join(", ")}) VALUES (${placeholders})`, values);
|
|
271
|
+
return { id, ...data, createdAt: now, updatedAt: now };
|
|
272
|
+
}
|
|
273
|
+
async update(params) {
|
|
274
|
+
if (!this.inTransaction) await this.ensureTable(params.collection);
|
|
275
|
+
const tableName = this.getTableName(params.collection);
|
|
276
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
277
|
+
const existingCols = cols.map((c) => c.Field);
|
|
278
|
+
const existing = await this.findOne({ collection: params.collection, id: params.id });
|
|
279
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
280
|
+
const merged = { ...existing ?? {}, ...params.data };
|
|
281
|
+
delete merged.id;
|
|
282
|
+
delete merged.createdAt;
|
|
283
|
+
delete merged.updatedAt;
|
|
284
|
+
const promotedValues = {};
|
|
285
|
+
for (const col of existingCols) {
|
|
286
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
287
|
+
if (merged[col] !== void 0) {
|
|
288
|
+
promotedValues[col] = merged[col];
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const setClauses = ["data = ?", "updated_at = ?", ...Object.keys(promotedValues).map((k) => `\`${k}\` = ?`)];
|
|
292
|
+
const values = [JSON.stringify(merged), now, ...Object.values(promotedValues), params.id];
|
|
293
|
+
await this.query(`UPDATE \`${tableName}\` SET ${setClauses.join(", ")} WHERE id = ?`, values);
|
|
294
|
+
return { id: params.id, ...merged, createdAt: existing?.createdAt, updatedAt: now };
|
|
295
|
+
}
|
|
296
|
+
async sync(collections) {
|
|
297
|
+
for (const col of collections) {
|
|
298
|
+
await this.ensureTable(col.slug, col.fields);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async delete(params) {
|
|
302
|
+
if (!this.inTransaction) await this.ensureTable(params.collection);
|
|
303
|
+
const tableName = this.getTableName(params.collection);
|
|
304
|
+
await this.query(`DELETE FROM \`${tableName}\` WHERE id = ?`, [params.id]);
|
|
305
|
+
}
|
|
306
|
+
async getGlobal(params) {
|
|
307
|
+
const [rows] = await this.query("SELECT value FROM dyrected_internal WHERE `key` = ?", [
|
|
308
|
+
`global_${params.slug}`
|
|
309
|
+
]);
|
|
310
|
+
const row = rows[0];
|
|
311
|
+
if (!row) return {};
|
|
312
|
+
return typeof row.value === "string" ? JSON.parse(row.value) : row.value;
|
|
313
|
+
}
|
|
314
|
+
async updateGlobal(params) {
|
|
315
|
+
await this.execute(
|
|
316
|
+
"INSERT INTO dyrected_internal (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)",
|
|
317
|
+
[`global_${params.slug}`, JSON.stringify(params.data)]
|
|
318
|
+
);
|
|
319
|
+
return params.data;
|
|
320
|
+
}
|
|
321
|
+
async transaction(callback) {
|
|
322
|
+
await this.ensureInitialized();
|
|
323
|
+
const connection = await this.pool.getConnection();
|
|
324
|
+
try {
|
|
325
|
+
await connection.beginTransaction();
|
|
326
|
+
const scoped = Object.create(this);
|
|
327
|
+
scoped.pool = connection;
|
|
328
|
+
scoped.initPromise = Promise.resolve();
|
|
329
|
+
scoped.inTransaction = true;
|
|
330
|
+
const result = await callback(scoped);
|
|
331
|
+
await connection.commit();
|
|
332
|
+
return result;
|
|
333
|
+
} catch (error) {
|
|
334
|
+
await connection.rollback();
|
|
335
|
+
throw error;
|
|
336
|
+
} finally {
|
|
337
|
+
connection.release();
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
341
|
+
async close() {
|
|
342
|
+
if (this.pool) {
|
|
343
|
+
await this.pool.end();
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
async aggregate(args) {
|
|
347
|
+
if (Object.keys(args.aggregates).length === 0) {
|
|
348
|
+
return {};
|
|
349
|
+
}
|
|
350
|
+
const tableName = this.getTableName(args.collection);
|
|
351
|
+
if (!this.inTransaction) await this.ensureTable(args.collection);
|
|
352
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
353
|
+
const existingCols = cols.map((c) => c.Field);
|
|
354
|
+
const toFieldExpr = (field) => {
|
|
355
|
+
if (field === "createdAt") return "`created_at`";
|
|
356
|
+
if (field === "updatedAt") return "`updated_at`";
|
|
357
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
358
|
+
return `\`${field}\``;
|
|
359
|
+
}
|
|
360
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}'))`;
|
|
361
|
+
};
|
|
362
|
+
const toCastExpr = (rawField, cast) => {
|
|
363
|
+
const base = toFieldExpr(rawField);
|
|
364
|
+
if (cast === "string") return base;
|
|
365
|
+
if (cast === "boolean") return `IF(${base} IS NOT NULL, IF(${base} IN ('true','1'), 1, 0), NULL)`;
|
|
366
|
+
if (cast === "date") return `CAST(${base} AS DATETIME)`;
|
|
367
|
+
const sqlType = cast === "integer" ? "SIGNED" : "DECIMAL(20,6)";
|
|
368
|
+
return `IF(${base} REGEXP '^-?[0-9]+(\\\\.[0-9]+)?([eE][+-]?[0-9]+)?$', CAST(${base} AS ${sqlType}), NULL)`;
|
|
369
|
+
};
|
|
370
|
+
const selectParts = [];
|
|
371
|
+
const allParams = [];
|
|
372
|
+
const isDistinctMap = {};
|
|
373
|
+
for (const [name, op] of Object.entries(args.aggregates)) {
|
|
374
|
+
let whereSql = null;
|
|
375
|
+
if (op.where && Object.keys(op.where).length > 0) {
|
|
376
|
+
const parsed = (0, import_core.parseSqlWhere)(op.where, toFieldExpr, "?");
|
|
377
|
+
whereSql = parsed.sql;
|
|
378
|
+
allParams.push(...parsed.params);
|
|
379
|
+
}
|
|
380
|
+
let aggExpr;
|
|
381
|
+
if ("countDistinct" in op && typeof op.countDistinct === "string") {
|
|
382
|
+
const fieldExpr = toFieldExpr(op.countDistinct);
|
|
383
|
+
aggExpr = whereSql ? `COUNT(DISTINCT IF(${whereSql}, ${fieldExpr}, NULL))` : `COUNT(DISTINCT ${fieldExpr})`;
|
|
384
|
+
} else if ("distinct" in op && typeof op.distinct === "string") {
|
|
385
|
+
isDistinctMap[name] = true;
|
|
386
|
+
const fieldExpr = toFieldExpr(op.distinct);
|
|
387
|
+
aggExpr = whereSql ? `COALESCE(JSON_ARRAYAGG(DISTINCT IF(${whereSql}, ${fieldExpr}, NULL)), JSON_ARRAY())` : `COALESCE(JSON_ARRAYAGG(DISTINCT ${fieldExpr}), JSON_ARRAY())`;
|
|
388
|
+
} else if ("count" in op) {
|
|
389
|
+
aggExpr = whereSql ? `COUNT(IF(${whereSql}, 1, NULL))` : `COUNT(*)`;
|
|
390
|
+
} else if (op.sum) {
|
|
391
|
+
const val = toCastExpr(op.sum, op.cast);
|
|
392
|
+
aggExpr = whereSql ? `SUM(IF(${whereSql}, ${val}, NULL))` : `SUM(${val})`;
|
|
393
|
+
} else if (op.avg) {
|
|
394
|
+
const val = toCastExpr(op.avg, op.cast);
|
|
395
|
+
aggExpr = whereSql ? `AVG(IF(${whereSql}, ${val}, NULL))` : `AVG(${val})`;
|
|
396
|
+
} else if (op.min) {
|
|
397
|
+
const val = toCastExpr(op.min, op.cast);
|
|
398
|
+
aggExpr = whereSql ? `MIN(IF(${whereSql}, ${val}, NULL))` : `MIN(${val})`;
|
|
399
|
+
} else if (op.max) {
|
|
400
|
+
const val = toCastExpr(op.max, op.cast);
|
|
401
|
+
aggExpr = whereSql ? `MAX(IF(${whereSql}, ${val}, NULL))` : `MAX(${val})`;
|
|
402
|
+
} else {
|
|
403
|
+
aggExpr = whereSql ? `COUNT(IF(${whereSql}, 1, NULL))` : `COUNT(*)`;
|
|
404
|
+
}
|
|
405
|
+
selectParts.push(
|
|
406
|
+
`${aggExpr} AS \`${name.replace(/`/g, "``")}\``
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
if (args.groupBy) {
|
|
410
|
+
const groupCol = toFieldExpr(args.groupBy);
|
|
411
|
+
const query2 = `SELECT ${groupCol} AS \`__group_key\`, ${selectParts.join(", ")} FROM \`${tableName}\` GROUP BY ${groupCol}`;
|
|
412
|
+
const [rows2] = await this.query(query2, allParams);
|
|
413
|
+
const groups = {};
|
|
414
|
+
for (const row2 of rows2 ?? []) {
|
|
415
|
+
const key = row2.__group_key === null || row2.__group_key === void 0 ? "__unassigned__" : String(row2.__group_key);
|
|
416
|
+
const groupResult = {};
|
|
417
|
+
for (const name of Object.keys(args.aggregates)) {
|
|
418
|
+
const raw = row2[name];
|
|
419
|
+
if (isDistinctMap[name]) {
|
|
420
|
+
const parsed = Array.isArray(raw) ? raw : typeof raw === "string" ? JSON.parse(raw) : raw ?? [];
|
|
421
|
+
groupResult[name] = Array.isArray(parsed) ? parsed.filter((v) => v !== null && v !== void 0) : [];
|
|
422
|
+
} else {
|
|
423
|
+
groupResult[name] = raw === null || raw === void 0 ? null : Number(raw);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
groups[key] = groupResult;
|
|
427
|
+
}
|
|
428
|
+
return { groups };
|
|
429
|
+
}
|
|
430
|
+
const query = `SELECT ${selectParts.join(", ")} FROM \`${tableName}\``;
|
|
431
|
+
const [rows] = await this.query(query, allParams);
|
|
432
|
+
const row = rows[0] ?? {};
|
|
433
|
+
const result = {};
|
|
434
|
+
for (const name of Object.keys(args.aggregates)) {
|
|
435
|
+
const raw = row[name];
|
|
436
|
+
if (isDistinctMap[name]) {
|
|
437
|
+
const parsed = Array.isArray(raw) ? raw : typeof raw === "string" ? JSON.parse(raw) : raw ?? [];
|
|
438
|
+
result[name] = Array.isArray(parsed) ? parsed.filter((v) => v !== null && v !== void 0) : [];
|
|
439
|
+
} else {
|
|
440
|
+
result[name] = raw === null || raw === void 0 ? null : Number(raw);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return result;
|
|
444
|
+
}
|
|
445
|
+
async disconnect() {
|
|
446
|
+
if (this.initPromise) {
|
|
447
|
+
try {
|
|
448
|
+
await this.initPromise;
|
|
449
|
+
} catch {
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (this.pool && typeof this.pool.end === "function") {
|
|
453
|
+
await this.pool.end().catch(() => {
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
this.initPromise = null;
|
|
457
|
+
this.pool = null;
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
var mysqlAdapter = (config) => new MysqlAdapter(config);
|
|
461
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
462
|
+
0 && (module.exports = {
|
|
463
|
+
MysqlAdapter,
|
|
464
|
+
mysqlAdapter
|
|
465
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { DatabaseAdapter, PaginatedResult } from '@dyrected/core';
|
|
2
|
+
|
|
3
|
+
interface MysqlAdapterConfig {
|
|
4
|
+
/** Full MySQL connection URL: mysql://user:pass@host:3306/dbname */
|
|
5
|
+
url?: string;
|
|
6
|
+
/** Alternative: individual connection options */
|
|
7
|
+
host?: string;
|
|
8
|
+
port?: number;
|
|
9
|
+
user?: string;
|
|
10
|
+
password?: string;
|
|
11
|
+
database?: string;
|
|
12
|
+
}
|
|
13
|
+
declare class MysqlAdapter implements DatabaseAdapter {
|
|
14
|
+
private pool;
|
|
15
|
+
private config;
|
|
16
|
+
private initPromise;
|
|
17
|
+
private inTransaction;
|
|
18
|
+
constructor(config: MysqlAdapterConfig);
|
|
19
|
+
private handleConnectionError;
|
|
20
|
+
private ensureInitialized;
|
|
21
|
+
private initialize;
|
|
22
|
+
private query;
|
|
23
|
+
execute(sql: string, params?: any[]): Promise<any>;
|
|
24
|
+
private getTableName;
|
|
25
|
+
private ensureTable;
|
|
26
|
+
find(args: {
|
|
27
|
+
collection: string;
|
|
28
|
+
where?: any;
|
|
29
|
+
limit?: number;
|
|
30
|
+
page?: number;
|
|
31
|
+
sort?: string;
|
|
32
|
+
}): Promise<PaginatedResult>;
|
|
33
|
+
findOne(params: {
|
|
34
|
+
collection: string;
|
|
35
|
+
id: string;
|
|
36
|
+
}): Promise<any>;
|
|
37
|
+
create(params: {
|
|
38
|
+
collection: string;
|
|
39
|
+
data: any;
|
|
40
|
+
}): Promise<any>;
|
|
41
|
+
update(params: {
|
|
42
|
+
collection: string;
|
|
43
|
+
id: string;
|
|
44
|
+
data: any;
|
|
45
|
+
}): Promise<any>;
|
|
46
|
+
sync(collections: any[]): Promise<void>;
|
|
47
|
+
delete(params: {
|
|
48
|
+
collection: string;
|
|
49
|
+
id: string;
|
|
50
|
+
}): Promise<void>;
|
|
51
|
+
getGlobal(params: {
|
|
52
|
+
slug: string;
|
|
53
|
+
}): Promise<any>;
|
|
54
|
+
updateGlobal(params: {
|
|
55
|
+
slug: string;
|
|
56
|
+
data: any;
|
|
57
|
+
}): Promise<any>;
|
|
58
|
+
transaction<T>(callback: (db: DatabaseAdapter) => Promise<T>): Promise<T>;
|
|
59
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
60
|
+
close(): Promise<void>;
|
|
61
|
+
aggregate(args: {
|
|
62
|
+
collection: string;
|
|
63
|
+
aggregates: Record<string, any>;
|
|
64
|
+
groupBy?: string;
|
|
65
|
+
}): Promise<Record<string, any>>;
|
|
66
|
+
disconnect(): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
declare const mysqlAdapter: (config: MysqlAdapterConfig) => MysqlAdapter;
|
|
69
|
+
|
|
70
|
+
export { MysqlAdapter, type MysqlAdapterConfig, mysqlAdapter };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { DatabaseAdapter, PaginatedResult } from '@dyrected/core';
|
|
2
|
+
|
|
3
|
+
interface MysqlAdapterConfig {
|
|
4
|
+
/** Full MySQL connection URL: mysql://user:pass@host:3306/dbname */
|
|
5
|
+
url?: string;
|
|
6
|
+
/** Alternative: individual connection options */
|
|
7
|
+
host?: string;
|
|
8
|
+
port?: number;
|
|
9
|
+
user?: string;
|
|
10
|
+
password?: string;
|
|
11
|
+
database?: string;
|
|
12
|
+
}
|
|
13
|
+
declare class MysqlAdapter implements DatabaseAdapter {
|
|
14
|
+
private pool;
|
|
15
|
+
private config;
|
|
16
|
+
private initPromise;
|
|
17
|
+
private inTransaction;
|
|
18
|
+
constructor(config: MysqlAdapterConfig);
|
|
19
|
+
private handleConnectionError;
|
|
20
|
+
private ensureInitialized;
|
|
21
|
+
private initialize;
|
|
22
|
+
private query;
|
|
23
|
+
execute(sql: string, params?: any[]): Promise<any>;
|
|
24
|
+
private getTableName;
|
|
25
|
+
private ensureTable;
|
|
26
|
+
find(args: {
|
|
27
|
+
collection: string;
|
|
28
|
+
where?: any;
|
|
29
|
+
limit?: number;
|
|
30
|
+
page?: number;
|
|
31
|
+
sort?: string;
|
|
32
|
+
}): Promise<PaginatedResult>;
|
|
33
|
+
findOne(params: {
|
|
34
|
+
collection: string;
|
|
35
|
+
id: string;
|
|
36
|
+
}): Promise<any>;
|
|
37
|
+
create(params: {
|
|
38
|
+
collection: string;
|
|
39
|
+
data: any;
|
|
40
|
+
}): Promise<any>;
|
|
41
|
+
update(params: {
|
|
42
|
+
collection: string;
|
|
43
|
+
id: string;
|
|
44
|
+
data: any;
|
|
45
|
+
}): Promise<any>;
|
|
46
|
+
sync(collections: any[]): Promise<void>;
|
|
47
|
+
delete(params: {
|
|
48
|
+
collection: string;
|
|
49
|
+
id: string;
|
|
50
|
+
}): Promise<void>;
|
|
51
|
+
getGlobal(params: {
|
|
52
|
+
slug: string;
|
|
53
|
+
}): Promise<any>;
|
|
54
|
+
updateGlobal(params: {
|
|
55
|
+
slug: string;
|
|
56
|
+
data: any;
|
|
57
|
+
}): Promise<any>;
|
|
58
|
+
transaction<T>(callback: (db: DatabaseAdapter) => Promise<T>): Promise<T>;
|
|
59
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
60
|
+
close(): Promise<void>;
|
|
61
|
+
aggregate(args: {
|
|
62
|
+
collection: string;
|
|
63
|
+
aggregates: Record<string, any>;
|
|
64
|
+
groupBy?: string;
|
|
65
|
+
}): Promise<Record<string, any>>;
|
|
66
|
+
disconnect(): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
declare const mysqlAdapter: (config: MysqlAdapterConfig) => MysqlAdapter;
|
|
69
|
+
|
|
70
|
+
export { MysqlAdapter, type MysqlAdapterConfig, mysqlAdapter };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { parseSort, parseSqlWhere } from "@dyrected/core";
|
|
3
|
+
import mysql from "mysql2/promise";
|
|
4
|
+
function escapeMysqlIdentifier(identifier) {
|
|
5
|
+
return `\`${identifier.replace(/`/g, "``")}\``;
|
|
6
|
+
}
|
|
7
|
+
function normalizeMysqlSort(sort, existingCols) {
|
|
8
|
+
return parseSort(sort).map(({ field, direction }) => {
|
|
9
|
+
if (field === "createdAt" || field === "created_at") return `\`created_at\` ${direction}`;
|
|
10
|
+
if (field === "updatedAt" || field === "updated_at") return `\`updated_at\` ${direction}`;
|
|
11
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
12
|
+
return `${escapeMysqlIdentifier(field)} ${direction}`;
|
|
13
|
+
}
|
|
14
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}')) ${direction}`;
|
|
15
|
+
}).join(", ");
|
|
16
|
+
}
|
|
17
|
+
var MysqlAdapter = class {
|
|
18
|
+
pool;
|
|
19
|
+
config;
|
|
20
|
+
initPromise = null;
|
|
21
|
+
inTransaction = false;
|
|
22
|
+
constructor(config) {
|
|
23
|
+
this.config = config;
|
|
24
|
+
}
|
|
25
|
+
handleConnectionError(err) {
|
|
26
|
+
if (err && (err.code === "EADDRNOTAVAIL" || err.message?.includes("EADDRNOTAVAIL"))) {
|
|
27
|
+
const customMessage = `
|
|
28
|
+
[dyrected/db-mysql] ERROR: MySQL connection failed with EADDRNOTAVAIL.
|
|
29
|
+
--------------------------------------------------------------------------------
|
|
30
|
+
This error often occurs when:
|
|
31
|
+
1. 'localhost' is resolved to an IPv6 address (::1) but MySQL is only listening on IPv4 (127.0.0.1).
|
|
32
|
+
2. The MySQL server is not running or is bound to a different port.
|
|
33
|
+
|
|
34
|
+
FIX INSTRUCTIONS:
|
|
35
|
+
- Try changing your host configuration in '.env' or config from 'localhost' to '127.0.0.1'.
|
|
36
|
+
- Make sure your local MySQL service is active and running on the configured port.
|
|
37
|
+
--------------------------------------------------------------------------------
|
|
38
|
+
`;
|
|
39
|
+
console.error(customMessage);
|
|
40
|
+
throw new Error(`MySQL Connection Failed: EADDRNOTAVAIL. Hint: Try using '127.0.0.1' instead of 'localhost'. Original: ${err.message}`);
|
|
41
|
+
}
|
|
42
|
+
throw err;
|
|
43
|
+
}
|
|
44
|
+
async ensureInitialized() {
|
|
45
|
+
if (!this.initPromise) {
|
|
46
|
+
this.initPromise = this.initialize();
|
|
47
|
+
}
|
|
48
|
+
await this.initPromise;
|
|
49
|
+
}
|
|
50
|
+
async initialize() {
|
|
51
|
+
const config = this.config;
|
|
52
|
+
let dbName = config.database;
|
|
53
|
+
let serverConfig = null;
|
|
54
|
+
if (config.url) {
|
|
55
|
+
try {
|
|
56
|
+
const parsed = new URL(config.url);
|
|
57
|
+
dbName = parsed.pathname.replace(/^\//, "");
|
|
58
|
+
const serverUrl = `${parsed.protocol}//${parsed.username}:${parsed.password}@${parsed.host}`;
|
|
59
|
+
serverConfig = serverUrl;
|
|
60
|
+
} catch (err) {
|
|
61
|
+
}
|
|
62
|
+
} else {
|
|
63
|
+
serverConfig = {
|
|
64
|
+
host: config.host ?? "localhost",
|
|
65
|
+
port: config.port ?? 3306,
|
|
66
|
+
user: config.user,
|
|
67
|
+
password: config.password
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (dbName && serverConfig) {
|
|
71
|
+
try {
|
|
72
|
+
const tempConn = await mysql.createConnection(serverConfig);
|
|
73
|
+
await tempConn.query(`CREATE DATABASE IF NOT EXISTS \`${dbName}\``);
|
|
74
|
+
await tempConn.end();
|
|
75
|
+
console.log(`[dyrected/db-mysql] Database "${dbName}" checked/created successfully`);
|
|
76
|
+
} catch (err) {
|
|
77
|
+
console.warn(`[dyrected/db-mysql] Auto-creation of database "${dbName}" skipped/failed:`, err.message);
|
|
78
|
+
if (err.code === "EADDRNOTAVAIL" || err.message?.includes("EADDRNOTAVAIL")) {
|
|
79
|
+
this.handleConnectionError(err);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (config.url) {
|
|
84
|
+
this.pool = mysql.createPool(config.url);
|
|
85
|
+
} else {
|
|
86
|
+
this.pool = mysql.createPool({
|
|
87
|
+
host: config.host ?? "localhost",
|
|
88
|
+
port: config.port ?? 3306,
|
|
89
|
+
user: config.user,
|
|
90
|
+
password: config.password,
|
|
91
|
+
database: config.database,
|
|
92
|
+
dateStrings: true
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
await this.pool.query(`
|
|
97
|
+
CREATE TABLE IF NOT EXISTS dyrected_internal (
|
|
98
|
+
\`key\` VARCHAR(255) PRIMARY KEY,
|
|
99
|
+
value JSON NOT NULL
|
|
100
|
+
)
|
|
101
|
+
`);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
this.handleConnectionError(err);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async query(sql, params) {
|
|
107
|
+
await this.ensureInitialized();
|
|
108
|
+
try {
|
|
109
|
+
return await this.pool.query(sql, params);
|
|
110
|
+
} catch (err) {
|
|
111
|
+
this.handleConnectionError(err);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async execute(sql, params) {
|
|
115
|
+
await this.ensureInitialized();
|
|
116
|
+
try {
|
|
117
|
+
return await this.pool.execute(sql, params);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
this.handleConnectionError(err);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
getTableName(slug) {
|
|
123
|
+
return `collection_${slug}`;
|
|
124
|
+
}
|
|
125
|
+
async ensureTable(slug, fields = []) {
|
|
126
|
+
const tableName = this.getTableName(slug);
|
|
127
|
+
await this.query(`
|
|
128
|
+
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
|
|
129
|
+
id VARCHAR(36) PRIMARY KEY,
|
|
130
|
+
data JSON NOT NULL,
|
|
131
|
+
created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3),
|
|
132
|
+
updated_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
|
133
|
+
)
|
|
134
|
+
`);
|
|
135
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
136
|
+
const existingCols = cols.map((c) => c.Field);
|
|
137
|
+
for (const field of fields) {
|
|
138
|
+
if (field.promoted && !existingCols.includes(field.name)) {
|
|
139
|
+
console.log(`[dyrected/mysql] Promoting field "${field.name}" to column in ${tableName}`);
|
|
140
|
+
let sqlType = "TEXT";
|
|
141
|
+
if (field.type === "number") sqlType = "DECIMAL(19,4)";
|
|
142
|
+
if (field.type === "boolean") sqlType = "TINYINT(1)";
|
|
143
|
+
await this.query(`ALTER TABLE \`${tableName}\` ADD COLUMN \`${field.name}\` ${sqlType}`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async find(args) {
|
|
148
|
+
if (!this.inTransaction) await this.ensureTable(args.collection);
|
|
149
|
+
const tableName = this.getTableName(args.collection);
|
|
150
|
+
const limit = args.limit ?? 10;
|
|
151
|
+
const page = args.page ?? 1;
|
|
152
|
+
const offset = (page - 1) * limit;
|
|
153
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
154
|
+
const existingCols = cols.map((c) => c.Field);
|
|
155
|
+
let whereSql = "";
|
|
156
|
+
let whereParams = [];
|
|
157
|
+
if (args.where && Object.keys(args.where).length > 0) {
|
|
158
|
+
const result = parseSqlWhere(
|
|
159
|
+
args.where,
|
|
160
|
+
(field) => {
|
|
161
|
+
if (field === "createdAt") return "`created_at`";
|
|
162
|
+
if (field === "updatedAt") return "`updated_at`";
|
|
163
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
164
|
+
return `\`${field}\``;
|
|
165
|
+
}
|
|
166
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}'))`;
|
|
167
|
+
},
|
|
168
|
+
"?"
|
|
169
|
+
);
|
|
170
|
+
whereSql = `WHERE ${result.sql}`;
|
|
171
|
+
whereParams = result.params;
|
|
172
|
+
}
|
|
173
|
+
const sort = normalizeMysqlSort(args.sort, existingCols);
|
|
174
|
+
const [countRows] = await this.query(
|
|
175
|
+
`SELECT COUNT(*) AS total FROM \`${tableName}\` ${whereSql}`,
|
|
176
|
+
whereParams
|
|
177
|
+
);
|
|
178
|
+
const total = Number(countRows[0].total);
|
|
179
|
+
const [rows] = await this.query(
|
|
180
|
+
`SELECT * FROM \`${tableName}\` ${whereSql} ORDER BY ${sort} LIMIT ? OFFSET ?`,
|
|
181
|
+
[...whereParams, limit, offset]
|
|
182
|
+
);
|
|
183
|
+
const docs = rows.map((r) => ({
|
|
184
|
+
id: r.id,
|
|
185
|
+
...JSON.parse(typeof r.data === "string" ? r.data : JSON.stringify(r.data)),
|
|
186
|
+
createdAt: r.created_at,
|
|
187
|
+
updatedAt: r.updated_at
|
|
188
|
+
}));
|
|
189
|
+
const totalPages = Math.ceil(total / limit);
|
|
190
|
+
return {
|
|
191
|
+
docs,
|
|
192
|
+
total,
|
|
193
|
+
limit,
|
|
194
|
+
page,
|
|
195
|
+
totalPages,
|
|
196
|
+
hasNextPage: page < totalPages,
|
|
197
|
+
hasPrevPage: page > 1
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
async findOne(params) {
|
|
201
|
+
if (!this.inTransaction) await this.ensureTable(params.collection);
|
|
202
|
+
const tableName = this.getTableName(params.collection);
|
|
203
|
+
const lock = this.inTransaction ? " FOR UPDATE" : "";
|
|
204
|
+
const [rows] = await this.query(`SELECT * FROM \`${tableName}\` WHERE id = ?${lock}`, [params.id]);
|
|
205
|
+
const row = rows[0];
|
|
206
|
+
if (!row) return null;
|
|
207
|
+
return {
|
|
208
|
+
id: row.id,
|
|
209
|
+
...JSON.parse(typeof row.data === "string" ? row.data : JSON.stringify(row.data)),
|
|
210
|
+
createdAt: row.created_at,
|
|
211
|
+
updatedAt: row.updated_at
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
async create(params) {
|
|
215
|
+
if (!this.inTransaction) await this.ensureTable(params.collection);
|
|
216
|
+
const tableName = this.getTableName(params.collection);
|
|
217
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
218
|
+
const existingCols = cols.map((c) => c.Field);
|
|
219
|
+
const id = params.data.id ?? Math.random().toString(36).substring(7);
|
|
220
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
221
|
+
const data = { ...params.data };
|
|
222
|
+
delete data.id;
|
|
223
|
+
delete data.createdAt;
|
|
224
|
+
delete data.updatedAt;
|
|
225
|
+
const promotedValues = {};
|
|
226
|
+
for (const col of existingCols) {
|
|
227
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
228
|
+
if (data[col] !== void 0) {
|
|
229
|
+
promotedValues[col] = data[col];
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const colNames = ["id", "data", "created_at", "updated_at", ...Object.keys(promotedValues).map((k) => `\`${k}\``)];
|
|
233
|
+
const placeholders = colNames.map(() => "?").join(", ");
|
|
234
|
+
const values = [id, JSON.stringify(data), now, now, ...Object.values(promotedValues)];
|
|
235
|
+
await this.query(`INSERT INTO \`${tableName}\` (${colNames.join(", ")}) VALUES (${placeholders})`, values);
|
|
236
|
+
return { id, ...data, createdAt: now, updatedAt: now };
|
|
237
|
+
}
|
|
238
|
+
async update(params) {
|
|
239
|
+
if (!this.inTransaction) await this.ensureTable(params.collection);
|
|
240
|
+
const tableName = this.getTableName(params.collection);
|
|
241
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
242
|
+
const existingCols = cols.map((c) => c.Field);
|
|
243
|
+
const existing = await this.findOne({ collection: params.collection, id: params.id });
|
|
244
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
245
|
+
const merged = { ...existing ?? {}, ...params.data };
|
|
246
|
+
delete merged.id;
|
|
247
|
+
delete merged.createdAt;
|
|
248
|
+
delete merged.updatedAt;
|
|
249
|
+
const promotedValues = {};
|
|
250
|
+
for (const col of existingCols) {
|
|
251
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
252
|
+
if (merged[col] !== void 0) {
|
|
253
|
+
promotedValues[col] = merged[col];
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const setClauses = ["data = ?", "updated_at = ?", ...Object.keys(promotedValues).map((k) => `\`${k}\` = ?`)];
|
|
257
|
+
const values = [JSON.stringify(merged), now, ...Object.values(promotedValues), params.id];
|
|
258
|
+
await this.query(`UPDATE \`${tableName}\` SET ${setClauses.join(", ")} WHERE id = ?`, values);
|
|
259
|
+
return { id: params.id, ...merged, createdAt: existing?.createdAt, updatedAt: now };
|
|
260
|
+
}
|
|
261
|
+
async sync(collections) {
|
|
262
|
+
for (const col of collections) {
|
|
263
|
+
await this.ensureTable(col.slug, col.fields);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
async delete(params) {
|
|
267
|
+
if (!this.inTransaction) await this.ensureTable(params.collection);
|
|
268
|
+
const tableName = this.getTableName(params.collection);
|
|
269
|
+
await this.query(`DELETE FROM \`${tableName}\` WHERE id = ?`, [params.id]);
|
|
270
|
+
}
|
|
271
|
+
async getGlobal(params) {
|
|
272
|
+
const [rows] = await this.query("SELECT value FROM dyrected_internal WHERE `key` = ?", [
|
|
273
|
+
`global_${params.slug}`
|
|
274
|
+
]);
|
|
275
|
+
const row = rows[0];
|
|
276
|
+
if (!row) return {};
|
|
277
|
+
return typeof row.value === "string" ? JSON.parse(row.value) : row.value;
|
|
278
|
+
}
|
|
279
|
+
async updateGlobal(params) {
|
|
280
|
+
await this.execute(
|
|
281
|
+
"INSERT INTO dyrected_internal (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)",
|
|
282
|
+
[`global_${params.slug}`, JSON.stringify(params.data)]
|
|
283
|
+
);
|
|
284
|
+
return params.data;
|
|
285
|
+
}
|
|
286
|
+
async transaction(callback) {
|
|
287
|
+
await this.ensureInitialized();
|
|
288
|
+
const connection = await this.pool.getConnection();
|
|
289
|
+
try {
|
|
290
|
+
await connection.beginTransaction();
|
|
291
|
+
const scoped = Object.create(this);
|
|
292
|
+
scoped.pool = connection;
|
|
293
|
+
scoped.initPromise = Promise.resolve();
|
|
294
|
+
scoped.inTransaction = true;
|
|
295
|
+
const result = await callback(scoped);
|
|
296
|
+
await connection.commit();
|
|
297
|
+
return result;
|
|
298
|
+
} catch (error) {
|
|
299
|
+
await connection.rollback();
|
|
300
|
+
throw error;
|
|
301
|
+
} finally {
|
|
302
|
+
connection.release();
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
306
|
+
async close() {
|
|
307
|
+
if (this.pool) {
|
|
308
|
+
await this.pool.end();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
async aggregate(args) {
|
|
312
|
+
if (Object.keys(args.aggregates).length === 0) {
|
|
313
|
+
return {};
|
|
314
|
+
}
|
|
315
|
+
const tableName = this.getTableName(args.collection);
|
|
316
|
+
if (!this.inTransaction) await this.ensureTable(args.collection);
|
|
317
|
+
const [cols] = await this.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
318
|
+
const existingCols = cols.map((c) => c.Field);
|
|
319
|
+
const toFieldExpr = (field) => {
|
|
320
|
+
if (field === "createdAt") return "`created_at`";
|
|
321
|
+
if (field === "updatedAt") return "`updated_at`";
|
|
322
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
323
|
+
return `\`${field}\``;
|
|
324
|
+
}
|
|
325
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}'))`;
|
|
326
|
+
};
|
|
327
|
+
const toCastExpr = (rawField, cast) => {
|
|
328
|
+
const base = toFieldExpr(rawField);
|
|
329
|
+
if (cast === "string") return base;
|
|
330
|
+
if (cast === "boolean") return `IF(${base} IS NOT NULL, IF(${base} IN ('true','1'), 1, 0), NULL)`;
|
|
331
|
+
if (cast === "date") return `CAST(${base} AS DATETIME)`;
|
|
332
|
+
const sqlType = cast === "integer" ? "SIGNED" : "DECIMAL(20,6)";
|
|
333
|
+
return `IF(${base} REGEXP '^-?[0-9]+(\\\\.[0-9]+)?([eE][+-]?[0-9]+)?$', CAST(${base} AS ${sqlType}), NULL)`;
|
|
334
|
+
};
|
|
335
|
+
const selectParts = [];
|
|
336
|
+
const allParams = [];
|
|
337
|
+
const isDistinctMap = {};
|
|
338
|
+
for (const [name, op] of Object.entries(args.aggregates)) {
|
|
339
|
+
let whereSql = null;
|
|
340
|
+
if (op.where && Object.keys(op.where).length > 0) {
|
|
341
|
+
const parsed = parseSqlWhere(op.where, toFieldExpr, "?");
|
|
342
|
+
whereSql = parsed.sql;
|
|
343
|
+
allParams.push(...parsed.params);
|
|
344
|
+
}
|
|
345
|
+
let aggExpr;
|
|
346
|
+
if ("countDistinct" in op && typeof op.countDistinct === "string") {
|
|
347
|
+
const fieldExpr = toFieldExpr(op.countDistinct);
|
|
348
|
+
aggExpr = whereSql ? `COUNT(DISTINCT IF(${whereSql}, ${fieldExpr}, NULL))` : `COUNT(DISTINCT ${fieldExpr})`;
|
|
349
|
+
} else if ("distinct" in op && typeof op.distinct === "string") {
|
|
350
|
+
isDistinctMap[name] = true;
|
|
351
|
+
const fieldExpr = toFieldExpr(op.distinct);
|
|
352
|
+
aggExpr = whereSql ? `COALESCE(JSON_ARRAYAGG(DISTINCT IF(${whereSql}, ${fieldExpr}, NULL)), JSON_ARRAY())` : `COALESCE(JSON_ARRAYAGG(DISTINCT ${fieldExpr}), JSON_ARRAY())`;
|
|
353
|
+
} else if ("count" in op) {
|
|
354
|
+
aggExpr = whereSql ? `COUNT(IF(${whereSql}, 1, NULL))` : `COUNT(*)`;
|
|
355
|
+
} else if (op.sum) {
|
|
356
|
+
const val = toCastExpr(op.sum, op.cast);
|
|
357
|
+
aggExpr = whereSql ? `SUM(IF(${whereSql}, ${val}, NULL))` : `SUM(${val})`;
|
|
358
|
+
} else if (op.avg) {
|
|
359
|
+
const val = toCastExpr(op.avg, op.cast);
|
|
360
|
+
aggExpr = whereSql ? `AVG(IF(${whereSql}, ${val}, NULL))` : `AVG(${val})`;
|
|
361
|
+
} else if (op.min) {
|
|
362
|
+
const val = toCastExpr(op.min, op.cast);
|
|
363
|
+
aggExpr = whereSql ? `MIN(IF(${whereSql}, ${val}, NULL))` : `MIN(${val})`;
|
|
364
|
+
} else if (op.max) {
|
|
365
|
+
const val = toCastExpr(op.max, op.cast);
|
|
366
|
+
aggExpr = whereSql ? `MAX(IF(${whereSql}, ${val}, NULL))` : `MAX(${val})`;
|
|
367
|
+
} else {
|
|
368
|
+
aggExpr = whereSql ? `COUNT(IF(${whereSql}, 1, NULL))` : `COUNT(*)`;
|
|
369
|
+
}
|
|
370
|
+
selectParts.push(
|
|
371
|
+
`${aggExpr} AS \`${name.replace(/`/g, "``")}\``
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
if (args.groupBy) {
|
|
375
|
+
const groupCol = toFieldExpr(args.groupBy);
|
|
376
|
+
const query2 = `SELECT ${groupCol} AS \`__group_key\`, ${selectParts.join(", ")} FROM \`${tableName}\` GROUP BY ${groupCol}`;
|
|
377
|
+
const [rows2] = await this.query(query2, allParams);
|
|
378
|
+
const groups = {};
|
|
379
|
+
for (const row2 of rows2 ?? []) {
|
|
380
|
+
const key = row2.__group_key === null || row2.__group_key === void 0 ? "__unassigned__" : String(row2.__group_key);
|
|
381
|
+
const groupResult = {};
|
|
382
|
+
for (const name of Object.keys(args.aggregates)) {
|
|
383
|
+
const raw = row2[name];
|
|
384
|
+
if (isDistinctMap[name]) {
|
|
385
|
+
const parsed = Array.isArray(raw) ? raw : typeof raw === "string" ? JSON.parse(raw) : raw ?? [];
|
|
386
|
+
groupResult[name] = Array.isArray(parsed) ? parsed.filter((v) => v !== null && v !== void 0) : [];
|
|
387
|
+
} else {
|
|
388
|
+
groupResult[name] = raw === null || raw === void 0 ? null : Number(raw);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
groups[key] = groupResult;
|
|
392
|
+
}
|
|
393
|
+
return { groups };
|
|
394
|
+
}
|
|
395
|
+
const query = `SELECT ${selectParts.join(", ")} FROM \`${tableName}\``;
|
|
396
|
+
const [rows] = await this.query(query, allParams);
|
|
397
|
+
const row = rows[0] ?? {};
|
|
398
|
+
const result = {};
|
|
399
|
+
for (const name of Object.keys(args.aggregates)) {
|
|
400
|
+
const raw = row[name];
|
|
401
|
+
if (isDistinctMap[name]) {
|
|
402
|
+
const parsed = Array.isArray(raw) ? raw : typeof raw === "string" ? JSON.parse(raw) : raw ?? [];
|
|
403
|
+
result[name] = Array.isArray(parsed) ? parsed.filter((v) => v !== null && v !== void 0) : [];
|
|
404
|
+
} else {
|
|
405
|
+
result[name] = raw === null || raw === void 0 ? null : Number(raw);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return result;
|
|
409
|
+
}
|
|
410
|
+
async disconnect() {
|
|
411
|
+
if (this.initPromise) {
|
|
412
|
+
try {
|
|
413
|
+
await this.initPromise;
|
|
414
|
+
} catch {
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
if (this.pool && typeof this.pool.end === "function") {
|
|
418
|
+
await this.pool.end().catch(() => {
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
this.initPromise = null;
|
|
422
|
+
this.pool = null;
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
var mysqlAdapter = (config) => new MysqlAdapter(config);
|
|
426
|
+
export {
|
|
427
|
+
MysqlAdapter,
|
|
428
|
+
mysqlAdapter
|
|
429
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dyrected/db-mysql",
|
|
3
|
+
"version": "0.0.0-pr-18-20260828214838",
|
|
4
|
+
"description": "MySQL adapter for Dyrected CMS",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist"
|
|
8
|
+
],
|
|
9
|
+
"main": "./dist/index.cjs",
|
|
10
|
+
"module": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.js",
|
|
16
|
+
"require": "./dist/index.cjs"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"mysql2": "^3.22.3",
|
|
21
|
+
"@dyrected/core": "^0.0.0-pr-18-20260828214838"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"tsup": "^8.0.0",
|
|
25
|
+
"typescript": "^5.0.0"
|
|
26
|
+
},
|
|
27
|
+
"license": "BUSL-1.1",
|
|
28
|
+
"homepage": "https://dyrected.com",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/Dyrected/dyrected.git"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
|
|
38
|
+
"dev": "tsup src/index.ts --format esm,cjs --dts --watch"
|
|
39
|
+
}
|
|
40
|
+
}
|