@dyrected/db-mysql 4.0.0
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/.turbo/turbo-build.log +62 -0
- package/CHANGELOG.md +28 -0
- package/LICENSE.md +50 -0
- package/README.md +3 -0
- package/dist/index.cjs +237 -0
- package/dist/index.d.cts +56 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.js +201 -0
- package/package.json +40 -0
- package/src/index.ts +261 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
> @dyrected/db-mysql@4.0.0 build /Users/busola/Work/dyrected/packages/db-mysql
|
|
4
|
+
> tsup src/index.ts --format esm,cjs --dts --clean
|
|
5
|
+
|
|
6
|
+
CLI Building entry: src/index.ts
|
|
7
|
+
CLI Using tsconfig: tsconfig.json
|
|
8
|
+
CLI tsup v8.5.1
|
|
9
|
+
CLI Target: esnext
|
|
10
|
+
CLI Cleaning output folder
|
|
11
|
+
ESM Build start
|
|
12
|
+
CJS Build start
|
|
13
|
+
|
|
14
|
+
[10:58:11 PM] WARN [33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mThe condition "types" here will never be used as it comes after both "import" and "require"[0m [package.json]
|
|
15
|
+
|
|
16
|
+
package.json:13:6:
|
|
17
|
+
[37m 13 │ [32m"types"[37m: "./dist/index.d.ts"
|
|
18
|
+
╵ [32m~~~~~~~[0m
|
|
19
|
+
|
|
20
|
+
The "import" condition comes earlier and will be used for all "import" statements:
|
|
21
|
+
|
|
22
|
+
package.json:11:6:
|
|
23
|
+
[37m 11 │ [32m"import"[37m: "./dist/index.js",
|
|
24
|
+
╵ [32m~~~~~~~~[0m
|
|
25
|
+
|
|
26
|
+
The "require" condition comes earlier and will be used for all "require" calls:
|
|
27
|
+
|
|
28
|
+
package.json:12:6:
|
|
29
|
+
[37m 12 │ [32m"require"[37m: "./dist/index.cjs",
|
|
30
|
+
╵ [32m~~~~~~~~~[0m
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
[10:58:11 PM] WARN [33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mThe condition "types" here will never be used as it comes after both "import" and "require"[0m [package.json]
|
|
36
|
+
|
|
37
|
+
package.json:13:6:
|
|
38
|
+
[37m 13 │ [32m"types"[37m: "./dist/index.d.ts"
|
|
39
|
+
╵ [32m~~~~~~~[0m
|
|
40
|
+
|
|
41
|
+
The "import" condition comes earlier and will be used for all "import" statements:
|
|
42
|
+
|
|
43
|
+
package.json:11:6:
|
|
44
|
+
[37m 11 │ [32m"import"[37m: "./dist/index.js",
|
|
45
|
+
╵ [32m~~~~~~~~[0m
|
|
46
|
+
|
|
47
|
+
The "require" condition comes earlier and will be used for all "require" calls:
|
|
48
|
+
|
|
49
|
+
package.json:12:6:
|
|
50
|
+
[37m 12 │ [32m"require"[37m: "./dist/index.cjs",
|
|
51
|
+
╵ [32m~~~~~~~~~[0m
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
CJS dist/index.cjs 9.32 KB
|
|
56
|
+
CJS ⚡️ Build success in 518ms
|
|
57
|
+
ESM dist/index.js 7.65 KB
|
|
58
|
+
ESM ⚡️ Build success in 519ms
|
|
59
|
+
DTS Build start
|
|
60
|
+
DTS ⚡️ Build success in 17150ms
|
|
61
|
+
DTS dist/index.d.ts 1.51 KB
|
|
62
|
+
DTS dist/index.d.cts 1.51 KB
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# @dyrected/db-mysql
|
|
2
|
+
|
|
3
|
+
## 4.0.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Infrastructure standardization, MySQL adapter improvements, and SDK robustness testing.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies
|
|
12
|
+
- @dyrected/core@2.4.0
|
|
13
|
+
|
|
14
|
+
## 3.0.0
|
|
15
|
+
|
|
16
|
+
### Minor Changes
|
|
17
|
+
|
|
18
|
+
- Standardize database infrastructure and implement field promotion.
|
|
19
|
+
- **Field Promotion**: Added 'promoted' option to Collection fields to extract JSON data into native SQL columns for indexing and performance.
|
|
20
|
+
- **Lazy Migrations**: Added 'renameTo' support for seamless field renames without breaking existing data.
|
|
21
|
+
- **Auto-Seeding**: Standardized 'initialData' seeding logic across all adapters.
|
|
22
|
+
- **MySQL Adapter**: New robust MySQL adapter implementation.
|
|
23
|
+
- **Strict Filtering**: Improved query translation parity across all SQL-based adapters.
|
|
24
|
+
|
|
25
|
+
### Patch Changes
|
|
26
|
+
|
|
27
|
+
- Updated dependencies
|
|
28
|
+
- @dyrected/core@2.3.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: Commercial use is permitted as long as it is not used to provide a hosted or managed service that competes with Dyrected.
|
|
8
|
+
Change Date: 2030-05-11
|
|
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,237 @@
|
|
|
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
|
+
var MysqlAdapter = class {
|
|
40
|
+
pool;
|
|
41
|
+
constructor(config) {
|
|
42
|
+
if (config.url) {
|
|
43
|
+
this.pool = import_promise.default.createPool(config.url);
|
|
44
|
+
} else {
|
|
45
|
+
this.pool = import_promise.default.createPool({
|
|
46
|
+
host: config.host ?? "localhost",
|
|
47
|
+
port: config.port ?? 3306,
|
|
48
|
+
user: config.user,
|
|
49
|
+
password: config.password,
|
|
50
|
+
database: config.database,
|
|
51
|
+
// Return dates as strings for consistency with other adapters
|
|
52
|
+
dateStrings: true
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
this.initInternalTables().catch((err) => console.error("[dyrected/db-mysql] Failed to init internal tables:", err));
|
|
56
|
+
}
|
|
57
|
+
async initInternalTables() {
|
|
58
|
+
await this.pool.query(`
|
|
59
|
+
CREATE TABLE IF NOT EXISTS dyrected_internal (
|
|
60
|
+
\`key\` VARCHAR(255) PRIMARY KEY,
|
|
61
|
+
value JSON NOT NULL
|
|
62
|
+
)
|
|
63
|
+
`);
|
|
64
|
+
}
|
|
65
|
+
getTableName(slug) {
|
|
66
|
+
return `collection_${slug}`;
|
|
67
|
+
}
|
|
68
|
+
async ensureTable(slug, fields = []) {
|
|
69
|
+
const tableName = this.getTableName(slug);
|
|
70
|
+
await this.pool.query(`
|
|
71
|
+
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
|
|
72
|
+
id VARCHAR(36) PRIMARY KEY,
|
|
73
|
+
data JSON NOT NULL,
|
|
74
|
+
created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3),
|
|
75
|
+
updated_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
|
76
|
+
)
|
|
77
|
+
`);
|
|
78
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
79
|
+
const existingCols = cols.map((c) => c.Field);
|
|
80
|
+
for (const field of fields) {
|
|
81
|
+
if (field.promoted && !existingCols.includes(field.name)) {
|
|
82
|
+
console.log(`[dyrected/mysql] Promoting field "${field.name}" to column in ${tableName}`);
|
|
83
|
+
let sqlType = "TEXT";
|
|
84
|
+
if (field.type === "number") sqlType = "DECIMAL(19,4)";
|
|
85
|
+
if (field.type === "boolean") sqlType = "TINYINT(1)";
|
|
86
|
+
await this.pool.query(`ALTER TABLE \`${tableName}\` ADD COLUMN \`${field.name}\` ${sqlType}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async find(args) {
|
|
91
|
+
await this.ensureTable(args.collection);
|
|
92
|
+
const tableName = this.getTableName(args.collection);
|
|
93
|
+
const limit = args.limit ?? 10;
|
|
94
|
+
const page = args.page ?? 1;
|
|
95
|
+
const offset = (page - 1) * limit;
|
|
96
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
97
|
+
const existingCols = cols.map((c) => c.Field);
|
|
98
|
+
let whereSql = "";
|
|
99
|
+
let whereParams = [];
|
|
100
|
+
if (args.where && Object.keys(args.where).length > 0) {
|
|
101
|
+
const result = (0, import_core.parseSqlWhere)(
|
|
102
|
+
args.where,
|
|
103
|
+
(field) => {
|
|
104
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
105
|
+
return `\`${field}\``;
|
|
106
|
+
}
|
|
107
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}'))`;
|
|
108
|
+
},
|
|
109
|
+
"?"
|
|
110
|
+
);
|
|
111
|
+
whereSql = `WHERE ${result.sql}`;
|
|
112
|
+
whereParams = result.params;
|
|
113
|
+
}
|
|
114
|
+
const rawSort = args.sort ?? "created_at DESC";
|
|
115
|
+
const sort = rawSort.replace(/\bcreatedAt\b/g, "created_at").replace(/\bupdatedAt\b/g, "updated_at");
|
|
116
|
+
const [countRows] = await this.pool.query(
|
|
117
|
+
`SELECT COUNT(*) AS total FROM \`${tableName}\` ${whereSql}`,
|
|
118
|
+
whereParams
|
|
119
|
+
);
|
|
120
|
+
const total = Number(countRows[0].total);
|
|
121
|
+
const [rows] = await this.pool.query(
|
|
122
|
+
`SELECT * FROM \`${tableName}\` ${whereSql} ORDER BY ${sort} LIMIT ? OFFSET ?`,
|
|
123
|
+
[...whereParams, limit, offset]
|
|
124
|
+
);
|
|
125
|
+
const docs = rows.map((r) => ({
|
|
126
|
+
id: r.id,
|
|
127
|
+
...JSON.parse(typeof r.data === "string" ? r.data : JSON.stringify(r.data)),
|
|
128
|
+
createdAt: r.created_at,
|
|
129
|
+
updatedAt: r.updated_at
|
|
130
|
+
}));
|
|
131
|
+
const totalPages = Math.ceil(total / limit);
|
|
132
|
+
return {
|
|
133
|
+
docs,
|
|
134
|
+
total,
|
|
135
|
+
limit,
|
|
136
|
+
page,
|
|
137
|
+
totalPages,
|
|
138
|
+
hasNextPage: page < totalPages,
|
|
139
|
+
hasPrevPage: page > 1
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
async findOne(params) {
|
|
143
|
+
await this.ensureTable(params.collection);
|
|
144
|
+
const tableName = this.getTableName(params.collection);
|
|
145
|
+
const [rows] = await this.pool.query(`SELECT * FROM \`${tableName}\` WHERE id = ?`, [params.id]);
|
|
146
|
+
const row = rows[0];
|
|
147
|
+
if (!row) return null;
|
|
148
|
+
return {
|
|
149
|
+
id: row.id,
|
|
150
|
+
...JSON.parse(typeof row.data === "string" ? row.data : JSON.stringify(row.data)),
|
|
151
|
+
createdAt: row.created_at,
|
|
152
|
+
updatedAt: row.updated_at
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
async create(params) {
|
|
156
|
+
await this.ensureTable(params.collection);
|
|
157
|
+
const tableName = this.getTableName(params.collection);
|
|
158
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
159
|
+
const existingCols = cols.map((c) => c.Field);
|
|
160
|
+
const id = params.data.id ?? Math.random().toString(36).substring(7);
|
|
161
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
162
|
+
const data = { ...params.data };
|
|
163
|
+
delete data.id;
|
|
164
|
+
delete data.createdAt;
|
|
165
|
+
delete data.updatedAt;
|
|
166
|
+
const promotedValues = {};
|
|
167
|
+
for (const col of existingCols) {
|
|
168
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
169
|
+
if (data[col] !== void 0) {
|
|
170
|
+
promotedValues[col] = data[col];
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const colNames = ["id", "data", "created_at", "updated_at", ...Object.keys(promotedValues).map((k) => `\`${k}\``)];
|
|
174
|
+
const placeholders = colNames.map(() => "?").join(", ");
|
|
175
|
+
const values = [id, JSON.stringify(data), now, now, ...Object.values(promotedValues)];
|
|
176
|
+
await this.pool.query(`INSERT INTO \`${tableName}\` (${colNames.join(", ")}) VALUES (${placeholders})`, values);
|
|
177
|
+
return { id, ...data, createdAt: now, updatedAt: now };
|
|
178
|
+
}
|
|
179
|
+
async update(params) {
|
|
180
|
+
await this.ensureTable(params.collection);
|
|
181
|
+
const tableName = this.getTableName(params.collection);
|
|
182
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
183
|
+
const existingCols = cols.map((c) => c.Field);
|
|
184
|
+
const existing = await this.findOne({ collection: params.collection, id: params.id });
|
|
185
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
186
|
+
const merged = { ...existing ?? {}, ...params.data };
|
|
187
|
+
delete merged.id;
|
|
188
|
+
delete merged.createdAt;
|
|
189
|
+
delete merged.updatedAt;
|
|
190
|
+
const promotedValues = {};
|
|
191
|
+
for (const col of existingCols) {
|
|
192
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
193
|
+
if (merged[col] !== void 0) {
|
|
194
|
+
promotedValues[col] = merged[col];
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const setClauses = ["data = ?", "updated_at = ?", ...Object.keys(promotedValues).map((k) => `\`${k}\` = ?`)];
|
|
198
|
+
const values = [JSON.stringify(merged), now, ...Object.values(promotedValues), params.id];
|
|
199
|
+
await this.pool.query(`UPDATE \`${tableName}\` SET ${setClauses.join(", ")} WHERE id = ?`, values);
|
|
200
|
+
return { id: params.id, ...merged, createdAt: existing?.createdAt, updatedAt: now };
|
|
201
|
+
}
|
|
202
|
+
async sync(collections) {
|
|
203
|
+
for (const col of collections) {
|
|
204
|
+
await this.ensureTable(col.slug, col.fields);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async delete(params) {
|
|
208
|
+
await this.ensureTable(params.collection);
|
|
209
|
+
const tableName = this.getTableName(params.collection);
|
|
210
|
+
await this.pool.query(`DELETE FROM \`${tableName}\` WHERE id = ?`, [params.id]);
|
|
211
|
+
}
|
|
212
|
+
async getGlobal(params) {
|
|
213
|
+
const [rows] = await this.pool.query("SELECT value FROM dyrected_internal WHERE `key` = ?", [
|
|
214
|
+
`global_${params.slug}`
|
|
215
|
+
]);
|
|
216
|
+
const row = rows[0];
|
|
217
|
+
if (!row) return {};
|
|
218
|
+
return typeof row.value === "string" ? JSON.parse(row.value) : row.value;
|
|
219
|
+
}
|
|
220
|
+
async updateGlobal(params) {
|
|
221
|
+
await this.pool.execute(
|
|
222
|
+
"INSERT INTO dyrected_internal (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)",
|
|
223
|
+
[`global_${params.slug}`, JSON.stringify(params.data)]
|
|
224
|
+
);
|
|
225
|
+
return params.data;
|
|
226
|
+
}
|
|
227
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
228
|
+
async close() {
|
|
229
|
+
await this.pool.end();
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
var mysqlAdapter = (config) => new MysqlAdapter(config);
|
|
233
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
234
|
+
0 && (module.exports = {
|
|
235
|
+
MysqlAdapter,
|
|
236
|
+
mysqlAdapter
|
|
237
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
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
|
+
constructor(config: MysqlAdapterConfig);
|
|
16
|
+
private initInternalTables;
|
|
17
|
+
private getTableName;
|
|
18
|
+
private ensureTable;
|
|
19
|
+
find(args: {
|
|
20
|
+
collection: string;
|
|
21
|
+
where?: any;
|
|
22
|
+
limit?: number;
|
|
23
|
+
page?: number;
|
|
24
|
+
sort?: string;
|
|
25
|
+
}): Promise<PaginatedResult>;
|
|
26
|
+
findOne(params: {
|
|
27
|
+
collection: string;
|
|
28
|
+
id: string;
|
|
29
|
+
}): Promise<any>;
|
|
30
|
+
create(params: {
|
|
31
|
+
collection: string;
|
|
32
|
+
data: any;
|
|
33
|
+
}): Promise<any>;
|
|
34
|
+
update(params: {
|
|
35
|
+
collection: string;
|
|
36
|
+
id: string;
|
|
37
|
+
data: any;
|
|
38
|
+
}): Promise<any>;
|
|
39
|
+
sync(collections: any[]): Promise<void>;
|
|
40
|
+
delete(params: {
|
|
41
|
+
collection: string;
|
|
42
|
+
id: string;
|
|
43
|
+
}): Promise<void>;
|
|
44
|
+
getGlobal(params: {
|
|
45
|
+
slug: string;
|
|
46
|
+
}): Promise<any>;
|
|
47
|
+
updateGlobal(params: {
|
|
48
|
+
slug: string;
|
|
49
|
+
data: any;
|
|
50
|
+
}): Promise<any>;
|
|
51
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
52
|
+
close(): Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
declare const mysqlAdapter: (config: MysqlAdapterConfig) => MysqlAdapter;
|
|
55
|
+
|
|
56
|
+
export { MysqlAdapter, type MysqlAdapterConfig, mysqlAdapter };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
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
|
+
constructor(config: MysqlAdapterConfig);
|
|
16
|
+
private initInternalTables;
|
|
17
|
+
private getTableName;
|
|
18
|
+
private ensureTable;
|
|
19
|
+
find(args: {
|
|
20
|
+
collection: string;
|
|
21
|
+
where?: any;
|
|
22
|
+
limit?: number;
|
|
23
|
+
page?: number;
|
|
24
|
+
sort?: string;
|
|
25
|
+
}): Promise<PaginatedResult>;
|
|
26
|
+
findOne(params: {
|
|
27
|
+
collection: string;
|
|
28
|
+
id: string;
|
|
29
|
+
}): Promise<any>;
|
|
30
|
+
create(params: {
|
|
31
|
+
collection: string;
|
|
32
|
+
data: any;
|
|
33
|
+
}): Promise<any>;
|
|
34
|
+
update(params: {
|
|
35
|
+
collection: string;
|
|
36
|
+
id: string;
|
|
37
|
+
data: any;
|
|
38
|
+
}): Promise<any>;
|
|
39
|
+
sync(collections: any[]): Promise<void>;
|
|
40
|
+
delete(params: {
|
|
41
|
+
collection: string;
|
|
42
|
+
id: string;
|
|
43
|
+
}): Promise<void>;
|
|
44
|
+
getGlobal(params: {
|
|
45
|
+
slug: string;
|
|
46
|
+
}): Promise<any>;
|
|
47
|
+
updateGlobal(params: {
|
|
48
|
+
slug: string;
|
|
49
|
+
data: any;
|
|
50
|
+
}): Promise<any>;
|
|
51
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
52
|
+
close(): Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
declare const mysqlAdapter: (config: MysqlAdapterConfig) => MysqlAdapter;
|
|
55
|
+
|
|
56
|
+
export { MysqlAdapter, type MysqlAdapterConfig, mysqlAdapter };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { parseSqlWhere } from "@dyrected/core";
|
|
3
|
+
import mysql from "mysql2/promise";
|
|
4
|
+
var MysqlAdapter = class {
|
|
5
|
+
pool;
|
|
6
|
+
constructor(config) {
|
|
7
|
+
if (config.url) {
|
|
8
|
+
this.pool = mysql.createPool(config.url);
|
|
9
|
+
} else {
|
|
10
|
+
this.pool = mysql.createPool({
|
|
11
|
+
host: config.host ?? "localhost",
|
|
12
|
+
port: config.port ?? 3306,
|
|
13
|
+
user: config.user,
|
|
14
|
+
password: config.password,
|
|
15
|
+
database: config.database,
|
|
16
|
+
// Return dates as strings for consistency with other adapters
|
|
17
|
+
dateStrings: true
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
this.initInternalTables().catch((err) => console.error("[dyrected/db-mysql] Failed to init internal tables:", err));
|
|
21
|
+
}
|
|
22
|
+
async initInternalTables() {
|
|
23
|
+
await this.pool.query(`
|
|
24
|
+
CREATE TABLE IF NOT EXISTS dyrected_internal (
|
|
25
|
+
\`key\` VARCHAR(255) PRIMARY KEY,
|
|
26
|
+
value JSON NOT NULL
|
|
27
|
+
)
|
|
28
|
+
`);
|
|
29
|
+
}
|
|
30
|
+
getTableName(slug) {
|
|
31
|
+
return `collection_${slug}`;
|
|
32
|
+
}
|
|
33
|
+
async ensureTable(slug, fields = []) {
|
|
34
|
+
const tableName = this.getTableName(slug);
|
|
35
|
+
await this.pool.query(`
|
|
36
|
+
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
|
|
37
|
+
id VARCHAR(36) PRIMARY KEY,
|
|
38
|
+
data JSON NOT NULL,
|
|
39
|
+
created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3),
|
|
40
|
+
updated_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
|
41
|
+
)
|
|
42
|
+
`);
|
|
43
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
44
|
+
const existingCols = cols.map((c) => c.Field);
|
|
45
|
+
for (const field of fields) {
|
|
46
|
+
if (field.promoted && !existingCols.includes(field.name)) {
|
|
47
|
+
console.log(`[dyrected/mysql] Promoting field "${field.name}" to column in ${tableName}`);
|
|
48
|
+
let sqlType = "TEXT";
|
|
49
|
+
if (field.type === "number") sqlType = "DECIMAL(19,4)";
|
|
50
|
+
if (field.type === "boolean") sqlType = "TINYINT(1)";
|
|
51
|
+
await this.pool.query(`ALTER TABLE \`${tableName}\` ADD COLUMN \`${field.name}\` ${sqlType}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async find(args) {
|
|
56
|
+
await this.ensureTable(args.collection);
|
|
57
|
+
const tableName = this.getTableName(args.collection);
|
|
58
|
+
const limit = args.limit ?? 10;
|
|
59
|
+
const page = args.page ?? 1;
|
|
60
|
+
const offset = (page - 1) * limit;
|
|
61
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
62
|
+
const existingCols = cols.map((c) => c.Field);
|
|
63
|
+
let whereSql = "";
|
|
64
|
+
let whereParams = [];
|
|
65
|
+
if (args.where && Object.keys(args.where).length > 0) {
|
|
66
|
+
const result = parseSqlWhere(
|
|
67
|
+
args.where,
|
|
68
|
+
(field) => {
|
|
69
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
70
|
+
return `\`${field}\``;
|
|
71
|
+
}
|
|
72
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}'))`;
|
|
73
|
+
},
|
|
74
|
+
"?"
|
|
75
|
+
);
|
|
76
|
+
whereSql = `WHERE ${result.sql}`;
|
|
77
|
+
whereParams = result.params;
|
|
78
|
+
}
|
|
79
|
+
const rawSort = args.sort ?? "created_at DESC";
|
|
80
|
+
const sort = rawSort.replace(/\bcreatedAt\b/g, "created_at").replace(/\bupdatedAt\b/g, "updated_at");
|
|
81
|
+
const [countRows] = await this.pool.query(
|
|
82
|
+
`SELECT COUNT(*) AS total FROM \`${tableName}\` ${whereSql}`,
|
|
83
|
+
whereParams
|
|
84
|
+
);
|
|
85
|
+
const total = Number(countRows[0].total);
|
|
86
|
+
const [rows] = await this.pool.query(
|
|
87
|
+
`SELECT * FROM \`${tableName}\` ${whereSql} ORDER BY ${sort} LIMIT ? OFFSET ?`,
|
|
88
|
+
[...whereParams, limit, offset]
|
|
89
|
+
);
|
|
90
|
+
const docs = rows.map((r) => ({
|
|
91
|
+
id: r.id,
|
|
92
|
+
...JSON.parse(typeof r.data === "string" ? r.data : JSON.stringify(r.data)),
|
|
93
|
+
createdAt: r.created_at,
|
|
94
|
+
updatedAt: r.updated_at
|
|
95
|
+
}));
|
|
96
|
+
const totalPages = Math.ceil(total / limit);
|
|
97
|
+
return {
|
|
98
|
+
docs,
|
|
99
|
+
total,
|
|
100
|
+
limit,
|
|
101
|
+
page,
|
|
102
|
+
totalPages,
|
|
103
|
+
hasNextPage: page < totalPages,
|
|
104
|
+
hasPrevPage: page > 1
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
async findOne(params) {
|
|
108
|
+
await this.ensureTable(params.collection);
|
|
109
|
+
const tableName = this.getTableName(params.collection);
|
|
110
|
+
const [rows] = await this.pool.query(`SELECT * FROM \`${tableName}\` WHERE id = ?`, [params.id]);
|
|
111
|
+
const row = rows[0];
|
|
112
|
+
if (!row) return null;
|
|
113
|
+
return {
|
|
114
|
+
id: row.id,
|
|
115
|
+
...JSON.parse(typeof row.data === "string" ? row.data : JSON.stringify(row.data)),
|
|
116
|
+
createdAt: row.created_at,
|
|
117
|
+
updatedAt: row.updated_at
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
async create(params) {
|
|
121
|
+
await this.ensureTable(params.collection);
|
|
122
|
+
const tableName = this.getTableName(params.collection);
|
|
123
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
124
|
+
const existingCols = cols.map((c) => c.Field);
|
|
125
|
+
const id = params.data.id ?? Math.random().toString(36).substring(7);
|
|
126
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
127
|
+
const data = { ...params.data };
|
|
128
|
+
delete data.id;
|
|
129
|
+
delete data.createdAt;
|
|
130
|
+
delete data.updatedAt;
|
|
131
|
+
const promotedValues = {};
|
|
132
|
+
for (const col of existingCols) {
|
|
133
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
134
|
+
if (data[col] !== void 0) {
|
|
135
|
+
promotedValues[col] = data[col];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const colNames = ["id", "data", "created_at", "updated_at", ...Object.keys(promotedValues).map((k) => `\`${k}\``)];
|
|
139
|
+
const placeholders = colNames.map(() => "?").join(", ");
|
|
140
|
+
const values = [id, JSON.stringify(data), now, now, ...Object.values(promotedValues)];
|
|
141
|
+
await this.pool.query(`INSERT INTO \`${tableName}\` (${colNames.join(", ")}) VALUES (${placeholders})`, values);
|
|
142
|
+
return { id, ...data, createdAt: now, updatedAt: now };
|
|
143
|
+
}
|
|
144
|
+
async update(params) {
|
|
145
|
+
await this.ensureTable(params.collection);
|
|
146
|
+
const tableName = this.getTableName(params.collection);
|
|
147
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
148
|
+
const existingCols = cols.map((c) => c.Field);
|
|
149
|
+
const existing = await this.findOne({ collection: params.collection, id: params.id });
|
|
150
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
151
|
+
const merged = { ...existing ?? {}, ...params.data };
|
|
152
|
+
delete merged.id;
|
|
153
|
+
delete merged.createdAt;
|
|
154
|
+
delete merged.updatedAt;
|
|
155
|
+
const promotedValues = {};
|
|
156
|
+
for (const col of existingCols) {
|
|
157
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
158
|
+
if (merged[col] !== void 0) {
|
|
159
|
+
promotedValues[col] = merged[col];
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const setClauses = ["data = ?", "updated_at = ?", ...Object.keys(promotedValues).map((k) => `\`${k}\` = ?`)];
|
|
163
|
+
const values = [JSON.stringify(merged), now, ...Object.values(promotedValues), params.id];
|
|
164
|
+
await this.pool.query(`UPDATE \`${tableName}\` SET ${setClauses.join(", ")} WHERE id = ?`, values);
|
|
165
|
+
return { id: params.id, ...merged, createdAt: existing?.createdAt, updatedAt: now };
|
|
166
|
+
}
|
|
167
|
+
async sync(collections) {
|
|
168
|
+
for (const col of collections) {
|
|
169
|
+
await this.ensureTable(col.slug, col.fields);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async delete(params) {
|
|
173
|
+
await this.ensureTable(params.collection);
|
|
174
|
+
const tableName = this.getTableName(params.collection);
|
|
175
|
+
await this.pool.query(`DELETE FROM \`${tableName}\` WHERE id = ?`, [params.id]);
|
|
176
|
+
}
|
|
177
|
+
async getGlobal(params) {
|
|
178
|
+
const [rows] = await this.pool.query("SELECT value FROM dyrected_internal WHERE `key` = ?", [
|
|
179
|
+
`global_${params.slug}`
|
|
180
|
+
]);
|
|
181
|
+
const row = rows[0];
|
|
182
|
+
if (!row) return {};
|
|
183
|
+
return typeof row.value === "string" ? JSON.parse(row.value) : row.value;
|
|
184
|
+
}
|
|
185
|
+
async updateGlobal(params) {
|
|
186
|
+
await this.pool.execute(
|
|
187
|
+
"INSERT INTO dyrected_internal (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)",
|
|
188
|
+
[`global_${params.slug}`, JSON.stringify(params.data)]
|
|
189
|
+
);
|
|
190
|
+
return params.data;
|
|
191
|
+
}
|
|
192
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
193
|
+
async close() {
|
|
194
|
+
await this.pool.end();
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
var mysqlAdapter = (config) => new MysqlAdapter(config);
|
|
198
|
+
export {
|
|
199
|
+
MysqlAdapter,
|
|
200
|
+
mysqlAdapter
|
|
201
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dyrected/db-mysql",
|
|
3
|
+
"version": "4.0.0",
|
|
4
|
+
"description": "MySQL adapter for Dyrected CMS",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"require": "./dist/index.cjs",
|
|
13
|
+
"types": "./dist/index.d.ts"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"mysql2": "^3.22.3",
|
|
18
|
+
"@dyrected/core": "^2.4.0"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"tsup": "^8.0.0",
|
|
22
|
+
"typescript": "^5.0.0"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"@dyrected/core": "*"
|
|
26
|
+
},
|
|
27
|
+
"license": "BUSL-1.1",
|
|
28
|
+
"homepage": "https://dyrected.com",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/she-WritesCode/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
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { DatabaseAdapter, PaginatedResult, parseSqlWhere } from "@dyrected/core";
|
|
2
|
+
import mysql from "mysql2/promise";
|
|
3
|
+
|
|
4
|
+
export interface MysqlAdapterConfig {
|
|
5
|
+
/** Full MySQL connection URL: mysql://user:pass@host:3306/dbname */
|
|
6
|
+
url?: string;
|
|
7
|
+
/** Alternative: individual connection options */
|
|
8
|
+
host?: string;
|
|
9
|
+
port?: number;
|
|
10
|
+
user?: string;
|
|
11
|
+
password?: string;
|
|
12
|
+
database?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class MysqlAdapter implements DatabaseAdapter {
|
|
16
|
+
private pool: any;
|
|
17
|
+
|
|
18
|
+
constructor(config: MysqlAdapterConfig) {
|
|
19
|
+
if (config.url) {
|
|
20
|
+
this.pool = mysql.createPool(config.url);
|
|
21
|
+
} else {
|
|
22
|
+
this.pool = mysql.createPool({
|
|
23
|
+
host: config.host ?? "localhost",
|
|
24
|
+
port: config.port ?? 3306,
|
|
25
|
+
user: config.user,
|
|
26
|
+
password: config.password,
|
|
27
|
+
database: config.database,
|
|
28
|
+
// Return dates as strings for consistency with other adapters
|
|
29
|
+
dateStrings: true,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
// Fire-and-forget: create internal table on startup
|
|
33
|
+
this.initInternalTables().catch((err) => console.error("[dyrected/db-mysql] Failed to init internal tables:", err));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private async initInternalTables() {
|
|
37
|
+
await this.pool.query(`
|
|
38
|
+
CREATE TABLE IF NOT EXISTS dyrected_internal (
|
|
39
|
+
\`key\` VARCHAR(255) PRIMARY KEY,
|
|
40
|
+
value JSON NOT NULL
|
|
41
|
+
)
|
|
42
|
+
`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private getTableName(slug: string): string {
|
|
46
|
+
return `collection_${slug}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private async ensureTable(slug: string, fields: any[] = []) {
|
|
50
|
+
const tableName = this.getTableName(slug);
|
|
51
|
+
await this.pool.query(`
|
|
52
|
+
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
|
|
53
|
+
id VARCHAR(36) PRIMARY KEY,
|
|
54
|
+
data JSON NOT NULL,
|
|
55
|
+
created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3),
|
|
56
|
+
updated_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
|
57
|
+
)
|
|
58
|
+
`);
|
|
59
|
+
|
|
60
|
+
// Inspect columns for promoted fields
|
|
61
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
62
|
+
const existingCols = cols.map((c: any) => c.Field);
|
|
63
|
+
|
|
64
|
+
for (const field of fields) {
|
|
65
|
+
if (field.promoted && !existingCols.includes(field.name)) {
|
|
66
|
+
console.log(`[dyrected/mysql] Promoting field "${field.name}" to column in ${tableName}`);
|
|
67
|
+
let sqlType = "TEXT";
|
|
68
|
+
if (field.type === "number") sqlType = "DECIMAL(19,4)";
|
|
69
|
+
if (field.type === "boolean") sqlType = "TINYINT(1)";
|
|
70
|
+
|
|
71
|
+
await this.pool.query(`ALTER TABLE \`${tableName}\` ADD COLUMN \`${field.name}\` ${sqlType}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async find(args: {
|
|
77
|
+
collection: string;
|
|
78
|
+
where?: any;
|
|
79
|
+
limit?: number;
|
|
80
|
+
page?: number;
|
|
81
|
+
sort?: string;
|
|
82
|
+
}): Promise<PaginatedResult> {
|
|
83
|
+
await this.ensureTable(args.collection);
|
|
84
|
+
const tableName = this.getTableName(args.collection);
|
|
85
|
+
|
|
86
|
+
const limit = args.limit ?? 10;
|
|
87
|
+
const page = args.page ?? 1;
|
|
88
|
+
const offset = (page - 1) * limit;
|
|
89
|
+
|
|
90
|
+
// Inspect columns for promoted fields
|
|
91
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
92
|
+
const existingCols = cols.map((c: any) => c.Field);
|
|
93
|
+
|
|
94
|
+
// Build WHERE clause via shared DSL translator (MySQL JSON path syntax)
|
|
95
|
+
let whereSql = "";
|
|
96
|
+
let whereParams: any[] = [];
|
|
97
|
+
if (args.where && Object.keys(args.where).length > 0) {
|
|
98
|
+
const result = parseSqlWhere(
|
|
99
|
+
args.where,
|
|
100
|
+
(field: string) => {
|
|
101
|
+
if (existingCols.includes(field) && !["id", "data"].includes(field)) {
|
|
102
|
+
return `\`${field}\``;
|
|
103
|
+
}
|
|
104
|
+
return `JSON_UNQUOTE(JSON_EXTRACT(data, '$.${field}'))`;
|
|
105
|
+
},
|
|
106
|
+
"?",
|
|
107
|
+
);
|
|
108
|
+
whereSql = `WHERE ${result.sql}`;
|
|
109
|
+
whereParams = result.params;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Normalize camelCase sort fields → snake_case columns
|
|
113
|
+
const rawSort = args.sort ?? "created_at DESC";
|
|
114
|
+
const sort = rawSort.replace(/\bcreatedAt\b/g, "created_at").replace(/\bupdatedAt\b/g, "updated_at");
|
|
115
|
+
|
|
116
|
+
// Count with filter applied for accurate pagination
|
|
117
|
+
const [countRows] = await this.pool.query(
|
|
118
|
+
`SELECT COUNT(*) AS total FROM \`${tableName}\` ${whereSql}`,
|
|
119
|
+
whereParams,
|
|
120
|
+
);
|
|
121
|
+
const total = Number(countRows[0].total);
|
|
122
|
+
|
|
123
|
+
// Fetch page of data
|
|
124
|
+
const [rows] = await this.pool.query(
|
|
125
|
+
`SELECT * FROM \`${tableName}\` ${whereSql} ORDER BY ${sort} LIMIT ? OFFSET ?`,
|
|
126
|
+
[...whereParams, limit, offset],
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
const docs = rows.map((r: any) => ({
|
|
130
|
+
id: r.id,
|
|
131
|
+
...JSON.parse(typeof r.data === "string" ? r.data : JSON.stringify(r.data)),
|
|
132
|
+
createdAt: r.created_at,
|
|
133
|
+
updatedAt: r.updated_at,
|
|
134
|
+
}));
|
|
135
|
+
|
|
136
|
+
const totalPages = Math.ceil(total / limit);
|
|
137
|
+
return {
|
|
138
|
+
docs,
|
|
139
|
+
total,
|
|
140
|
+
limit,
|
|
141
|
+
page,
|
|
142
|
+
totalPages,
|
|
143
|
+
hasNextPage: page < totalPages,
|
|
144
|
+
hasPrevPage: page > 1,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async findOne(params: { collection: string; id: string }) {
|
|
149
|
+
await this.ensureTable(params.collection);
|
|
150
|
+
const tableName = this.getTableName(params.collection);
|
|
151
|
+
const [rows] = await this.pool.query(`SELECT * FROM \`${tableName}\` WHERE id = ?`, [params.id]);
|
|
152
|
+
const row = rows[0];
|
|
153
|
+
if (!row) return null;
|
|
154
|
+
return {
|
|
155
|
+
id: row.id,
|
|
156
|
+
...JSON.parse(typeof row.data === "string" ? row.data : JSON.stringify(row.data)),
|
|
157
|
+
createdAt: row.created_at,
|
|
158
|
+
updatedAt: row.updated_at,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async create(params: { collection: string; data: any }) {
|
|
163
|
+
await this.ensureTable(params.collection);
|
|
164
|
+
const tableName = this.getTableName(params.collection);
|
|
165
|
+
|
|
166
|
+
// Inspect columns for promoted fields
|
|
167
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
168
|
+
const existingCols = cols.map((c: any) => c.Field);
|
|
169
|
+
|
|
170
|
+
const id = params.data.id ?? Math.random().toString(36).substring(7);
|
|
171
|
+
const now = new Date().toISOString().replace("T", " ").replace("Z", "");
|
|
172
|
+
|
|
173
|
+
const data = { ...params.data };
|
|
174
|
+
delete data.id;
|
|
175
|
+
delete data.createdAt;
|
|
176
|
+
delete data.updatedAt;
|
|
177
|
+
|
|
178
|
+
// Extract promoted fields
|
|
179
|
+
const promotedValues: Record<string, any> = {};
|
|
180
|
+
for (const col of existingCols) {
|
|
181
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
182
|
+
if (data[col] !== undefined) {
|
|
183
|
+
promotedValues[col] = data[col];
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const colNames = ["id", "data", "created_at", "updated_at", ...Object.keys(promotedValues).map((k) => `\`${k}\``)];
|
|
188
|
+
const placeholders = colNames.map(() => "?").join(", ");
|
|
189
|
+
const values = [id, JSON.stringify(data), now, now, ...Object.values(promotedValues)];
|
|
190
|
+
|
|
191
|
+
await this.pool.query(`INSERT INTO \`${tableName}\` (${colNames.join(", ")}) VALUES (${placeholders})`, values);
|
|
192
|
+
return { id, ...data, createdAt: now, updatedAt: now };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async update(params: { collection: string; id: string; data: any }) {
|
|
196
|
+
await this.ensureTable(params.collection);
|
|
197
|
+
const tableName = this.getTableName(params.collection);
|
|
198
|
+
|
|
199
|
+
// Inspect columns for promoted fields
|
|
200
|
+
const [cols] = await this.pool.query(`SHOW COLUMNS FROM \`${tableName}\``);
|
|
201
|
+
const existingCols = cols.map((c: any) => c.Field);
|
|
202
|
+
|
|
203
|
+
const existing = await this.findOne({ collection: params.collection, id: params.id });
|
|
204
|
+
const now = new Date().toISOString().replace("T", " ").replace("Z", "");
|
|
205
|
+
const merged = { ...(existing ?? {}), ...params.data };
|
|
206
|
+
delete (merged as any).id;
|
|
207
|
+
delete (merged as any).createdAt;
|
|
208
|
+
delete (merged as any).updatedAt;
|
|
209
|
+
|
|
210
|
+
// Extract promoted fields
|
|
211
|
+
const promotedValues: Record<string, any> = {};
|
|
212
|
+
for (const col of existingCols) {
|
|
213
|
+
if (["id", "data", "created_at", "updated_at"].includes(col)) continue;
|
|
214
|
+
if (merged[col] !== undefined) {
|
|
215
|
+
promotedValues[col] = merged[col];
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const setClauses = ["data = ?", "updated_at = ?", ...Object.keys(promotedValues).map((k) => `\`${k}\` = ?`)];
|
|
220
|
+
const values = [JSON.stringify(merged), now, ...Object.values(promotedValues), params.id];
|
|
221
|
+
|
|
222
|
+
await this.pool.query(`UPDATE \`${tableName}\` SET ${setClauses.join(", ")} WHERE id = ?`, values);
|
|
223
|
+
return { id: params.id, ...merged, createdAt: existing?.createdAt, updatedAt: now };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async sync(collections: any[]) {
|
|
227
|
+
for (const col of collections) {
|
|
228
|
+
await this.ensureTable(col.slug, col.fields);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async delete(params: { collection: string; id: string }) {
|
|
233
|
+
await this.ensureTable(params.collection);
|
|
234
|
+
const tableName = this.getTableName(params.collection);
|
|
235
|
+
await this.pool.query(`DELETE FROM \`${tableName}\` WHERE id = ?`, [params.id]);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async getGlobal(params: { slug: string }) {
|
|
239
|
+
const [rows] = await this.pool.query("SELECT value FROM dyrected_internal WHERE `key` = ?", [
|
|
240
|
+
`global_${params.slug}`,
|
|
241
|
+
]);
|
|
242
|
+
const row = rows[0];
|
|
243
|
+
if (!row) return {};
|
|
244
|
+
return typeof row.value === "string" ? JSON.parse(row.value) : row.value;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async updateGlobal(params: { slug: string; data: any }) {
|
|
248
|
+
await this.pool.execute(
|
|
249
|
+
"INSERT INTO dyrected_internal (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)",
|
|
250
|
+
[`global_${params.slug}`, JSON.stringify(params.data)],
|
|
251
|
+
);
|
|
252
|
+
return params.data;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Gracefully close the connection pool. Call on process exit. */
|
|
256
|
+
async close() {
|
|
257
|
+
await this.pool.end();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export const mysqlAdapter = (config: MysqlAdapterConfig) => new MysqlAdapter(config);
|