jsql-neo 5.5.0 → 6.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/LICENSE +202 -202
- package/README.md +8155 -8097
- package/bin/jsql +320 -320
- package/bin/jsql-server +90 -90
- package/bin/jsql-server-control.js +177 -177
- package/index.d.ts +412 -385
- package/index.js +128 -124
- package/lib/ast.js +214 -214
- package/lib/btree.js +478 -413
- package/lib/cache.js +328 -328
- package/lib/client.js +125 -125
- package/lib/database.js +1741 -1744
- package/lib/date-types.js +182 -182
- package/lib/errors.js +89 -89
- package/lib/jsql_format.js +497 -497
- package/lib/migrate.js +254 -254
- package/lib/mod.js +292 -292
- package/lib/mongo_server.js +607 -607
- package/lib/multiserver.js +140 -140
- package/lib/mysql_compat.js +413 -413
- package/lib/mysql_server.js +1237 -1237
- package/lib/native_client.js +722 -732
- package/lib/nedb_compat.js +506 -506
- package/lib/pg_server.js +864 -864
- package/lib/plugin.js +259 -35
- package/lib/plugins/audit.js +37 -0
- package/lib/plugins/index.js +72 -0
- package/lib/plugins/logger.js +35 -0
- package/lib/plugins/metrics.js +38 -0
- package/lib/plugins/timestamps.js +57 -0
- package/lib/plugins/validation.js +128 -0
- package/lib/prepared.js +37 -0
- package/lib/query.js +834 -815
- package/lib/redis_server.js +571 -571
- package/lib/sql.js +4053 -3460
- package/lib/sqlite_compat.js +323 -323
- package/lib/sqlite_worker.js +264 -264
- package/lib/table.js +1351 -1304
- package/lib/tui.js +502 -502
- package/lib/wasm.js +1 -1
- package/lib/wasm_client.js +715 -718
- package/lib/web_ui.js +257 -257
- package/native/jsql-neo-native.node +0 -0
- package/nativesrc/jsql-neo-core/Cargo.lock +462 -455
- package/nativesrc/jsql-neo-core/Cargo.toml +26 -24
- package/nativesrc/jsql-neo-core/src/engine/hybrid.rs +492 -455
- package/nativesrc/jsql-neo-core/src/engine/memory.rs +191 -168
- package/nativesrc/jsql-neo-core/src/engine/mod.rs +74 -62
- package/nativesrc/jsql-neo-core/src/engine/table.rs +996 -700
- package/nativesrc/jsql-neo-core/src/lib.rs +2 -2
- package/nativesrc/jsql-neo-core/src/storage/mod.rs +2 -2
- package/nativesrc/jsql-neo-core/src/storage/persistent.rs +1 -1
- package/nativesrc/jsql-neo-core/src/storage/wal.rs +298 -85
- package/nativesrc/jsql-neo-core/src/types.rs +93 -93
- package/nativesrc/jsql-neo-native/Cargo.lock +613 -606
- package/nativesrc/jsql-neo-native/Cargo.toml +24 -16
- package/nativesrc/jsql-neo-native/build.rs +3 -3
- package/nativesrc/jsql-neo-native/package.json +7 -7
- package/nativesrc/jsql-neo-native/src/lib.rs +281 -269
- package/nativesrc/jsql-neo-wasm/Cargo.lock +472 -465
- package/nativesrc/jsql-neo-wasm/Cargo.toml +22 -15
- package/nativesrc/jsql-neo-wasm/src/lib.rs +463 -447
- package/package.json +87 -87
- package/postinstall.js +158 -158
- package/test/btree.test.js +144 -128
- package/test/coverage.js +187 -187
- package/test/join.test.js +110 -110
- package/test/native.test.js +158 -158
- package/test/query-opt.test.js +109 -0
- package/test/regress-5.1.0.js +271 -271
- package/test/smoke.js +58 -58
- package/test/sql-parser.test.js +450 -273
- package/test/wasm.test.js +110 -110
- package/wasm/browser.d.ts +89 -89
- package/wasm/browser.mjs +591 -569
- package/wasm/browser_bg.mjs +618 -597
- package/wasm/jsql_neo_wasm.d.ts +44 -38
- package/wasm/jsql_neo_wasm.js +641 -520
- package/wasm/jsql_neo_wasm_bg.wasm +0 -0
- package/wasm/jsql_neo_wasm_bg.wasm.d.ts +26 -26
- package/wasm/package.json +11 -11
package/lib/plugin.js
CHANGED
|
@@ -1,35 +1,259 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
1
|
+
/**
|
|
2
|
+
* JSQL-NEO 可编程插件系统
|
|
3
|
+
*
|
|
4
|
+
* 统一的插件运行时,被 native / wasm / js 三个引擎共用,开放四类扩展点:
|
|
5
|
+
* 1. 生命周期钩子(HOOKS)——在引擎操作前后触发,返回 false 可中止操作;
|
|
6
|
+
* 2. 事件监听(onEvent / emit)——操作完成后广播;
|
|
7
|
+
* 3. 上下文接口(ctx)——插件拿到引擎能力、schema、日志、配置与私有存储;
|
|
8
|
+
* 4. 插件 API(api / db.plugin(name))——插件对外暴露可编程接口。
|
|
9
|
+
*
|
|
10
|
+
* 约定:钩子内不要调用会再次触发钩子的引擎方法(native 引擎会抛
|
|
11
|
+
* ER_PLUGIN_REENTRY 保护 N-API 不崩溃);需要修改数据时直接原地修改传入的
|
|
12
|
+
* 数组 / 对象,返回 undefined;返回 false 表示中止本次操作。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** 内置生命周期钩子名(自定义钩子名也会被自动登记,无需在此声明) */
|
|
16
|
+
const HOOKS = Object.freeze([
|
|
17
|
+
'beforeInsert', 'afterInsert',
|
|
18
|
+
'beforeUpdate', 'afterUpdate',
|
|
19
|
+
'beforeDelete', 'afterDelete',
|
|
20
|
+
'beforeFind', 'afterFind',
|
|
21
|
+
'beforeCreateTable', 'afterCreateTable',
|
|
22
|
+
'beforeDropTable', 'afterDropTable',
|
|
23
|
+
'beforeFlush', 'afterFlush',
|
|
24
|
+
'beforeCount', 'afterCount',
|
|
25
|
+
'beforeQuery', 'afterQuery',
|
|
26
|
+
'onStart', 'onStop'
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
/** 创建一个预置了全部内置钩子的空注册表 */
|
|
30
|
+
function createHookRegistry() {
|
|
31
|
+
const reg = {};
|
|
32
|
+
for (const h of HOOKS) reg[h] = [];
|
|
33
|
+
return reg;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
class Plugin {
|
|
37
|
+
/**
|
|
38
|
+
* @param {string} name 插件名(用于 db.plugin(name) 取 API、私有存储隔离)
|
|
39
|
+
* @param {object} [opts]
|
|
40
|
+
* @param {string} [opts.version]
|
|
41
|
+
* @param {object} [opts.hooks] { hookName: fn | fn[] }
|
|
42
|
+
* @param {string[]} [opts.depends] 依赖的其它插件名
|
|
43
|
+
* @param {number} [opts.priority]
|
|
44
|
+
* @param {object} [opts.config] 传给插件的配置
|
|
45
|
+
* @param {object} [opts.api] 插件对外暴露的接口对象
|
|
46
|
+
* @param {function} [opts.onEvent]
|
|
47
|
+
* @param {function} [opts.install] install(engine, ctx)
|
|
48
|
+
*/
|
|
49
|
+
constructor(name, opts = {}) {
|
|
50
|
+
this.name = name;
|
|
51
|
+
this.version = opts.version || null;
|
|
52
|
+
this.hooks = opts.hooks || {};
|
|
53
|
+
this.depends = opts.depends || [];
|
|
54
|
+
this.priority = opts.priority || 0;
|
|
55
|
+
this.config = opts.config || {};
|
|
56
|
+
this.api = opts.api || null;
|
|
57
|
+
this._onEvent = opts.onEvent || null;
|
|
58
|
+
this._install = opts.install || null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
onEvent(fn) {
|
|
62
|
+
this._onEvent = fn;
|
|
63
|
+
return this;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 注册钩子;同名钩子可多次注册,按注册顺序执行 */
|
|
67
|
+
on(hook, fn) {
|
|
68
|
+
if (!this.hooks[hook]) this.hooks[hook] = [];
|
|
69
|
+
if (!Array.isArray(this.hooks[hook])) this.hooks[hook] = [this.hooks[hook]];
|
|
70
|
+
this.hooks[hook].push(fn);
|
|
71
|
+
return this;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
install(fn) {
|
|
75
|
+
this._install = fn;
|
|
76
|
+
return this;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 声明插件对外暴露的接口 */
|
|
80
|
+
expose(api) {
|
|
81
|
+
this.api = api;
|
|
82
|
+
return this;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
build() {
|
|
86
|
+
const inst = {
|
|
87
|
+
name: this.name,
|
|
88
|
+
version: this.version,
|
|
89
|
+
hooks: this.hooks,
|
|
90
|
+
depends: this.depends,
|
|
91
|
+
priority: this.priority,
|
|
92
|
+
config: this.config
|
|
93
|
+
};
|
|
94
|
+
if (this.api) inst.api = this.api;
|
|
95
|
+
if (this._onEvent) inst.onEvent = this._onEvent;
|
|
96
|
+
if (this._install) inst.install = this._install;
|
|
97
|
+
return inst;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 以函数式风格定义插件:definePlugin('name', { hooks, api, install }) */
|
|
102
|
+
function definePlugin(name, def = {}) {
|
|
103
|
+
return new Plugin(name, def).build();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 登记单个钩子;未知钩子名会自动创建,便于插件自定义扩展点 */
|
|
107
|
+
function registerHook(engine, hook, fn) {
|
|
108
|
+
if (typeof fn !== 'function') return engine;
|
|
109
|
+
if (!engine._hooks) engine._hooks = createHookRegistry();
|
|
110
|
+
if (!engine._hooks[hook]) engine._hooks[hook] = [];
|
|
111
|
+
engine._hooks[hook].push(fn);
|
|
112
|
+
return engine;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 把一个插件声明的所有钩子登记到引擎上 */
|
|
116
|
+
function registerHooks(engine, plugin) {
|
|
117
|
+
if (!plugin || !plugin.hooks) return engine;
|
|
118
|
+
for (const [hook, val] of Object.entries(plugin.hooks)) {
|
|
119
|
+
const fns = Array.isArray(val) ? val : [val];
|
|
120
|
+
for (const fn of fns) registerHook(engine, hook, fn);
|
|
121
|
+
}
|
|
122
|
+
return engine;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 引擎 → 插件 API 注册表 */
|
|
126
|
+
function getPluginApis(engine) {
|
|
127
|
+
if (!engine._pluginApis) engine._pluginApis = new Map();
|
|
128
|
+
return engine._pluginApis;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 引擎 → 插件私有存储(按插件名隔离) */
|
|
132
|
+
function getPluginStore(engine, name) {
|
|
133
|
+
if (!engine._pluginStores) engine._pluginStores = new Map();
|
|
134
|
+
if (!engine._pluginStores.has(name)) engine._pluginStores.set(name, new Map());
|
|
135
|
+
return engine._pluginStores.get(name);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 构建插件上下文。优先走引擎自身的公开方法,缺失时回退到约定的内部字段,
|
|
140
|
+
* 使三个引擎共享同一套插件 API。
|
|
141
|
+
*/
|
|
142
|
+
function buildPluginContext(engine, plugin) {
|
|
143
|
+
const name = plugin.name || 'anonymous';
|
|
144
|
+
const version = plugin.version || null;
|
|
145
|
+
const store = getPluginStore(engine, name);
|
|
146
|
+
const ctx = {
|
|
147
|
+
name,
|
|
148
|
+
version,
|
|
149
|
+
engine,
|
|
150
|
+
plugin,
|
|
151
|
+
config: plugin.config || {},
|
|
152
|
+
store,
|
|
153
|
+
/** 注册生命周期钩子 / 自定义钩子 */
|
|
154
|
+
on(hook, fn) { return engine.on(hook, fn); },
|
|
155
|
+
/** 注册事件监听 */
|
|
156
|
+
onEvent(fn) { return engine.onEvent(fn); },
|
|
157
|
+
/** 广播事件 */
|
|
158
|
+
emit(eventName, data) { return engine.emit(eventName, data); },
|
|
159
|
+
/** 主动触发一个钩子(含自定义钩子) */
|
|
160
|
+
hook(hookName, ...args) { return engine.runHook(hookName, ...args); },
|
|
161
|
+
/** 组合:加载另一个插件 */
|
|
162
|
+
use(other, opts) { return engine.use(other, opts); },
|
|
163
|
+
/** 表清单(同步) */
|
|
164
|
+
tables() {
|
|
165
|
+
if (engine._tableNames) return Array.from(engine._tableNames);
|
|
166
|
+
if (typeof engine.getTables === 'function') return engine.getTables();
|
|
167
|
+
return [];
|
|
168
|
+
},
|
|
169
|
+
/** 表是否存在 */
|
|
170
|
+
hasTable(t) {
|
|
171
|
+
if (typeof engine.hasTable === 'function') return engine.hasTable(t);
|
|
172
|
+
return !!(engine._tableNames && engine._tableNames.has(t));
|
|
173
|
+
},
|
|
174
|
+
/** 表 schema(同步,可能为 null) */
|
|
175
|
+
getTableSchema(t) {
|
|
176
|
+
if (engine._schemas && engine._schemas[t] !== undefined) return engine._schemas[t];
|
|
177
|
+
if (typeof engine.getTableSchema === 'function') return engine.getTableSchema(t);
|
|
178
|
+
return null;
|
|
179
|
+
},
|
|
180
|
+
/** 带插件名前缀的日志 */
|
|
181
|
+
log(...args) { console.log(`[jsql:${name}]`, ...args); },
|
|
182
|
+
/** 运行期声明插件 API */
|
|
183
|
+
expose(api) {
|
|
184
|
+
plugin.api = api;
|
|
185
|
+
getPluginApis(engine).set(name, api);
|
|
186
|
+
return api;
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
return ctx;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* 把一个插件应用到引擎:登记钩子、调用 install、挂载事件与 API。
|
|
194
|
+
* 引擎的 `use()` 只需 `return applyPlugin(this, plugin, opts)`。
|
|
195
|
+
* @returns {object} engine(便于链式调用)
|
|
196
|
+
*/
|
|
197
|
+
function applyPlugin(engine, plugin, opts) {
|
|
198
|
+
// 字符串 → 内置插件名(懒加载,避免与 plugins/index 形成加载期循环依赖)
|
|
199
|
+
if (typeof plugin === 'string') {
|
|
200
|
+
plugin = require('./plugins').resolve(plugin, opts);
|
|
201
|
+
}
|
|
202
|
+
if (typeof plugin === 'function') plugin = { install: plugin };
|
|
203
|
+
if (!plugin || typeof plugin !== 'object') {
|
|
204
|
+
throw new Error('use: plugin must be an object, a function, or a builtin plugin name');
|
|
205
|
+
}
|
|
206
|
+
if (!engine._plugins) engine._plugins = [];
|
|
207
|
+
if (!engine._eventListeners) engine._eventListeners = [];
|
|
208
|
+
|
|
209
|
+
registerHooks(engine, plugin);
|
|
210
|
+
|
|
211
|
+
const ctx = buildPluginContext(engine, plugin);
|
|
212
|
+
if (typeof plugin.install === 'function') plugin.install(engine, ctx);
|
|
213
|
+
if (typeof plugin.onEvent === 'function') engine._eventListeners.push(plugin.onEvent);
|
|
214
|
+
|
|
215
|
+
engine._plugins.push(plugin);
|
|
216
|
+
if (plugin.name && plugin.api) getPluginApis(engine).set(plugin.name, plugin.api);
|
|
217
|
+
return engine;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 运行某个钩子链。
|
|
222
|
+
* - 任一钩子返回 false → 中止(返回 false),引擎据此跳过本次操作;
|
|
223
|
+
* - native 引擎置 `_forbidReentry`,钩子内再次触发引擎操作会抛 ER_PLUGIN_REENTRY。
|
|
224
|
+
*/
|
|
225
|
+
function runHooks(engine, hookName, args) {
|
|
226
|
+
const hooks = engine._hooks && engine._hooks[hookName];
|
|
227
|
+
if (!hooks || hooks.length === 0) return true;
|
|
228
|
+
|
|
229
|
+
const guard = !!engine._forbidReentry;
|
|
230
|
+
if (guard) {
|
|
231
|
+
if (engine._inHook) {
|
|
232
|
+
throw new Error('ER_PLUGIN_REENTRY: plugin hook "' + hookName +
|
|
233
|
+
'" re-entered native call; plugin must not call engine methods inside its own hook');
|
|
234
|
+
}
|
|
235
|
+
engine._inHook = true;
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
for (const fn of hooks) {
|
|
239
|
+
if (fn(...args) === false) return false;
|
|
240
|
+
}
|
|
241
|
+
return true;
|
|
242
|
+
} finally {
|
|
243
|
+
if (guard) engine._inHook = false;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
module.exports = {
|
|
248
|
+
HOOKS,
|
|
249
|
+
Plugin,
|
|
250
|
+
definePlugin,
|
|
251
|
+
createHookRegistry,
|
|
252
|
+
registerHook,
|
|
253
|
+
registerHooks,
|
|
254
|
+
buildPluginContext,
|
|
255
|
+
applyPlugin,
|
|
256
|
+
runHooks,
|
|
257
|
+
getPluginApis,
|
|
258
|
+
getPluginStore
|
|
259
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* audit —— 记录数据变更审计日志(内存环形缓冲)。
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* db.use(require('jsql-neo/lib/plugins').audit({ limit: 500 }));
|
|
6
|
+
* db.plugin('audit').entries(); // [{ at, op, table, count }]
|
|
7
|
+
*/
|
|
8
|
+
const { definePlugin } = require('../plugin');
|
|
9
|
+
|
|
10
|
+
function createAudit(opts = {}) {
|
|
11
|
+
const limit = opts.limit || 1000;
|
|
12
|
+
const entries = [];
|
|
13
|
+
|
|
14
|
+
const push = e => {
|
|
15
|
+
entries.push({ at: Date.now(), ...e });
|
|
16
|
+
if (entries.length > limit) entries.splice(0, entries.length - limit);
|
|
17
|
+
};
|
|
18
|
+
const rowCount = rows => (Array.isArray(rows) ? rows.length : 1);
|
|
19
|
+
|
|
20
|
+
return definePlugin('audit', {
|
|
21
|
+
config: { limit },
|
|
22
|
+
api: {
|
|
23
|
+
entries: () => entries.map(e => ({ ...e })),
|
|
24
|
+
size: () => entries.length,
|
|
25
|
+
clear: () => { entries.length = 0; }
|
|
26
|
+
},
|
|
27
|
+
hooks: {
|
|
28
|
+
afterInsert(table, rows) { push({ op: 'insert', table, count: rowCount(rows) }); },
|
|
29
|
+
afterUpdate(table) { push({ op: 'update', table }); },
|
|
30
|
+
afterDelete(table) { push({ op: 'delete', table }); },
|
|
31
|
+
afterCreateTable(name) { push({ op: 'createTable', table: name }); },
|
|
32
|
+
afterDropTable(name) { push({ op: 'dropTable', table: name }); }
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
module.exports = { createAudit, audit: createAudit };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSQL-NEO 内置插件集
|
|
3
|
+
*
|
|
4
|
+
* 每个插件都是「工厂函数」,调用后返回可交给 `db.use()` 的插件对象。
|
|
5
|
+
* 也可以直接用名字加载:`db.use('logger')` / `db.use('timestamps', { ... })`。
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const plugins = require('jsql-neo/lib/plugins');
|
|
9
|
+
* db.use(plugins.timestamps());
|
|
10
|
+
* db.use(plugins.logger({ logger: myLog }));
|
|
11
|
+
* db.use(plugins.metrics());
|
|
12
|
+
* const audit = db.plugin('audit');
|
|
13
|
+
*/
|
|
14
|
+
const { createTimestamps } = require('./timestamps');
|
|
15
|
+
const { createLogger } = require('./logger');
|
|
16
|
+
const { createMetrics } = require('./metrics');
|
|
17
|
+
const { createAudit } = require('./audit');
|
|
18
|
+
const { createValidation } = require('./validation');
|
|
19
|
+
|
|
20
|
+
/** 名称 → 插件工厂 */
|
|
21
|
+
const builtins = {
|
|
22
|
+
timestamps: createTimestamps,
|
|
23
|
+
logger: createLogger,
|
|
24
|
+
metrics: createMetrics,
|
|
25
|
+
audit: createAudit,
|
|
26
|
+
validation: createValidation
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** 内置插件名清单 */
|
|
30
|
+
function list() {
|
|
31
|
+
return Object.keys(builtins);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 按名字构造内置插件。
|
|
36
|
+
* @param {string} name
|
|
37
|
+
* @param {object} [opts]
|
|
38
|
+
* @returns {object} 插件对象,可直接 db.use()
|
|
39
|
+
*/
|
|
40
|
+
function create(name, opts = {}) {
|
|
41
|
+
const factory = builtins[name];
|
|
42
|
+
if (!factory) {
|
|
43
|
+
throw new Error(`Unknown builtin plugin: ${name}. Available: ${list().join(', ')}`);
|
|
44
|
+
}
|
|
45
|
+
return factory(opts);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 名称或插件对象 → 插件对象。供引擎的 `use()` 解析字符串用。
|
|
50
|
+
* 插件对象原样返回;字符串走内置注册表。
|
|
51
|
+
*/
|
|
52
|
+
function resolve(nameOrPlugin, opts) {
|
|
53
|
+
if (typeof nameOrPlugin === 'string') return create(nameOrPlugin, opts);
|
|
54
|
+
return nameOrPlugin;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = {
|
|
58
|
+
createTimestamps,
|
|
59
|
+
createLogger,
|
|
60
|
+
createMetrics,
|
|
61
|
+
createAudit,
|
|
62
|
+
createValidation,
|
|
63
|
+
timestamps: createTimestamps,
|
|
64
|
+
logger: createLogger,
|
|
65
|
+
metrics: createMetrics,
|
|
66
|
+
audit: createAudit,
|
|
67
|
+
validation: createValidation,
|
|
68
|
+
builtins,
|
|
69
|
+
list,
|
|
70
|
+
create,
|
|
71
|
+
resolve
|
|
72
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* logger —— 把数据库操作记录到自定义 logger。
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* db.use(require('jsql-neo/lib/plugins').logger({ logger: myLogger, tables: ['users'] }));
|
|
6
|
+
*/
|
|
7
|
+
const { definePlugin } = require('../plugin');
|
|
8
|
+
|
|
9
|
+
function count(rows) {
|
|
10
|
+
if (Array.isArray(rows)) return rows.length;
|
|
11
|
+
return rows === undefined || rows === null ? 0 : 1;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function createLogger(opts = {}) {
|
|
15
|
+
const logger = typeof opts.logger === 'function' ? opts.logger : (...a) => console.log('[jsql]', ...a);
|
|
16
|
+
const only = opts.tables ? new Set(opts.tables) : null;
|
|
17
|
+
const show = t => !only || only.has(t);
|
|
18
|
+
|
|
19
|
+
return definePlugin('logger', {
|
|
20
|
+
config: { tables: opts.tables || null },
|
|
21
|
+
hooks: {
|
|
22
|
+
afterInsert(table, rows) { if (show(table)) logger(`insert ${table} +${count(rows)}`); },
|
|
23
|
+
afterUpdate(table) { if (show(table)) logger(`update ${table}`); },
|
|
24
|
+
afterDelete(table) { if (show(table)) logger(`delete ${table}`); },
|
|
25
|
+
afterFind(table) { if (opts.logFinds && show(table)) logger(`find ${table}`); },
|
|
26
|
+
afterQuery(sql) { if (opts.logQueries) logger(`query ${sql}`); },
|
|
27
|
+
afterCreateTable(name) { if (show(name)) logger(`createTable ${name}`); },
|
|
28
|
+
afterDropTable(name) { if (show(name)) logger(`dropTable ${name}`); },
|
|
29
|
+
onStart() { logger('engine start'); },
|
|
30
|
+
onStop() { logger('engine stop'); }
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { createLogger, logger: createLogger };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* metrics —— 统计各类操作的次数,通过 db.plugin('metrics') 读取。
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* db.use(require('jsql-neo/lib/plugins').metrics());
|
|
6
|
+
* db.plugin('metrics').snapshot(); // { insert: 3, update: 1, find: 5, ... }
|
|
7
|
+
* db.plugin('metrics').reset();
|
|
8
|
+
*/
|
|
9
|
+
const { definePlugin } = require('../plugin');
|
|
10
|
+
|
|
11
|
+
function createMetrics(opts = {}) {
|
|
12
|
+
const counters = {};
|
|
13
|
+
|
|
14
|
+
const bump = (key, n = 1) => { counters[key] = (counters[key] || 0) + n; };
|
|
15
|
+
const rowCount = rows => (Array.isArray(rows) ? rows.length : 1);
|
|
16
|
+
|
|
17
|
+
return definePlugin('metrics', {
|
|
18
|
+
api: {
|
|
19
|
+
snapshot: () => ({ ...counters }),
|
|
20
|
+
get: key => counters[key] || 0,
|
|
21
|
+
reset: () => { for (const k of Object.keys(counters)) delete counters[k]; }
|
|
22
|
+
},
|
|
23
|
+
hooks: {
|
|
24
|
+
afterInsert(_t, rows) { bump('insert', rowCount(rows)); bump('insertOps'); },
|
|
25
|
+
afterUpdate() { bump('update'); },
|
|
26
|
+
afterDelete() { bump('delete'); },
|
|
27
|
+
afterFind() { bump('find'); },
|
|
28
|
+
afterCount() { bump('count'); },
|
|
29
|
+
afterQuery() { bump('query'); },
|
|
30
|
+
afterCreateTable() { bump('createTable'); },
|
|
31
|
+
afterDropTable() { bump('dropTable'); },
|
|
32
|
+
onStart() { bump('start'); },
|
|
33
|
+
onStop() { bump('stop'); }
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { createMetrics, metrics: createMetrics };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* timestamps —— 自动维护创建/更新时间戳。
|
|
3
|
+
*
|
|
4
|
+
* 在插入时补全 createdAt / updatedAt(已存在则不覆盖 createdAt),
|
|
5
|
+
* 更新时刷新 updatedAt。建表时若 schema 未声明这两个字段,会原地补上,
|
|
6
|
+
* 以便 native / WASM 引擎按 schema 列持久化。钩子内只原地修改数据、不回调引擎。
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* db.use(require('jsql-neo/lib/plugins').timestamps());
|
|
10
|
+
* db.use(require('jsql-neo/lib/plugins').timestamps({ createdField: 'created_at', updatedField: 'updated_at' }));
|
|
11
|
+
*/
|
|
12
|
+
const { definePlugin } = require('../plugin');
|
|
13
|
+
|
|
14
|
+
function createTimestamps(opts = {}) {
|
|
15
|
+
const createdField = opts.createdField || 'createdAt';
|
|
16
|
+
const updatedField = opts.updatedField || 'updatedAt';
|
|
17
|
+
const now = typeof opts.now === 'function' ? opts.now : () => new Date().toISOString();
|
|
18
|
+
|
|
19
|
+
const stampRow = (row, isInsert) => {
|
|
20
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) return;
|
|
21
|
+
const t = now();
|
|
22
|
+
if (isInsert && row[createdField] === undefined) row[createdField] = t;
|
|
23
|
+
if (row[updatedField] === undefined || opts.overwriteUpdated) row[updatedField] = t;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const stampDef = { type: 'string' };
|
|
27
|
+
|
|
28
|
+
const ensureStampFields = (schema) => {
|
|
29
|
+
if (!schema) return;
|
|
30
|
+
if (typeof schema === 'string') return;
|
|
31
|
+
if (typeof schema !== 'object') return;
|
|
32
|
+
if (schema[createdField] === undefined) schema[createdField] = { ...stampDef };
|
|
33
|
+
if (schema[updatedField] === undefined) schema[updatedField] = { ...stampDef };
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
return definePlugin('timestamps', {
|
|
37
|
+
config: { createdField, updatedField },
|
|
38
|
+
hooks: {
|
|
39
|
+
beforeCreateTable(_name, schema) {
|
|
40
|
+
ensureStampFields(schema);
|
|
41
|
+
},
|
|
42
|
+
beforeInsert(_table, rows) {
|
|
43
|
+
if (Array.isArray(rows)) rows.forEach(r => stampRow(r, true));
|
|
44
|
+
else stampRow(rows, true);
|
|
45
|
+
},
|
|
46
|
+
// 更新钩子有 [table, id, data] / [table, pairs] / [table, query, updates] 三种形态
|
|
47
|
+
beforeUpdate(_table, second, third) {
|
|
48
|
+
if (third !== undefined) { stampRow(third, false); return; }
|
|
49
|
+
if (Array.isArray(second)) {
|
|
50
|
+
for (const pair of second) if (Array.isArray(pair)) stampRow(pair[1], false);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = { createTimestamps, timestamps: createTimestamps };
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* validation —— 基于表 schema 的插入/更新校验,跨引擎行为一致。
|
|
3
|
+
*
|
|
4
|
+
* 校验项:not null(插入)、字段类型、maxLength、min/max,以及自定义校验函数。
|
|
5
|
+
* 违反时抛出 `ER_VALIDATION: table.field ...`。
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* db.use(require('jsql-neo/lib/plugins').validation({
|
|
9
|
+
* validators: { users: { email: v => /@/.test(v) || 'invalid email' } }
|
|
10
|
+
* }));
|
|
11
|
+
*/
|
|
12
|
+
const { definePlugin } = require('../plugin');
|
|
13
|
+
|
|
14
|
+
function normalizeFieldDef(def) {
|
|
15
|
+
if (typeof def === 'string') {
|
|
16
|
+
const s = def.toLowerCase();
|
|
17
|
+
const has = re => new RegExp(re).test(s);
|
|
18
|
+
const type = s
|
|
19
|
+
.replace(/\bprimary\s+key\b/g, '')
|
|
20
|
+
.replace(/\bauto_?increment\b/g, '')
|
|
21
|
+
.replace(/\bnot\s+null\b/g, '')
|
|
22
|
+
.replace(/\bunique\b/g, '')
|
|
23
|
+
.replace(/\bdefault\s+\S+/g, '')
|
|
24
|
+
.trim();
|
|
25
|
+
return {
|
|
26
|
+
type: type || 'string',
|
|
27
|
+
required: has('\\bnot\\s+null\\b'),
|
|
28
|
+
primaryKey: has('\\bprimary\\s+key\\b'),
|
|
29
|
+
autoIncrement: has('\\bauto_?increment\\b'),
|
|
30
|
+
hasDefault: has('\\bdefault\\s+\\S+')
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
if (def && typeof def === 'object') {
|
|
34
|
+
return {
|
|
35
|
+
type: String(def.type || 'string').toLowerCase(),
|
|
36
|
+
required: !!(def.required || def.notNull || def.not_null),
|
|
37
|
+
nullable: def.nullable,
|
|
38
|
+
primaryKey: !!(def.primaryKey || def.primary_key),
|
|
39
|
+
autoIncrement: !!(def.autoIncrement || def.auto_increment),
|
|
40
|
+
hasDefault: def.default !== undefined,
|
|
41
|
+
maxLength: def.maxLength !== undefined ? def.maxLength : def.length,
|
|
42
|
+
min: def.min,
|
|
43
|
+
max: def.max
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return { type: 'string' };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const TYPE_OF = {
|
|
50
|
+
string: v => typeof v === 'string',
|
|
51
|
+
text: v => typeof v === 'string',
|
|
52
|
+
varchar: v => typeof v === 'string',
|
|
53
|
+
char: v => typeof v === 'string',
|
|
54
|
+
integer: v => Number.isInteger(v),
|
|
55
|
+
int: v => Number.isInteger(v),
|
|
56
|
+
bigint: v => typeof v === 'bigint' || Number.isInteger(v),
|
|
57
|
+
float: v => typeof v === 'number' && Number.isFinite(v),
|
|
58
|
+
double: v => typeof v === 'number' && Number.isFinite(v),
|
|
59
|
+
number: v => typeof v === 'number' && Number.isFinite(v),
|
|
60
|
+
numeric: v => typeof v === 'number' && Number.isFinite(v),
|
|
61
|
+
decimal: v => typeof v === 'number' && Number.isFinite(v),
|
|
62
|
+
boolean: v => typeof v === 'boolean',
|
|
63
|
+
bool: v => typeof v === 'boolean',
|
|
64
|
+
json: v => typeof v === 'object' && v !== null && !Array.isArray(v),
|
|
65
|
+
object: v => typeof v === 'object' && v !== null && !Array.isArray(v),
|
|
66
|
+
array: v => Array.isArray(v),
|
|
67
|
+
date: v => typeof v === 'string' || v instanceof Date,
|
|
68
|
+
datetime: v => typeof v === 'string' || v instanceof Date,
|
|
69
|
+
timestamp: v => typeof v === 'string' || v instanceof Date
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
function checkValue(table, field, def, value, row, custom) {
|
|
73
|
+
const isNull = value === undefined || value === null;
|
|
74
|
+
const fail = msg => { throw new Error(`ER_VALIDATION: ${table}.${field} ${msg}`); };
|
|
75
|
+
|
|
76
|
+
if (isNull) {
|
|
77
|
+
if (def.required && !def.hasDefault && def.nullable !== true) fail('is required');
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const type = def.type;
|
|
81
|
+
const checker = TYPE_OF[type];
|
|
82
|
+
if (checker && !checker(value)) fail(`expected ${type}, got ${typeof value}`);
|
|
83
|
+
if (def.maxLength !== undefined && typeof value === 'string' && value.length > def.maxLength) {
|
|
84
|
+
fail(`length > ${def.maxLength}`);
|
|
85
|
+
}
|
|
86
|
+
if (def.min !== undefined && typeof value === 'number' && value < def.min) fail(`< ${def.min}`);
|
|
87
|
+
if (def.max !== undefined && typeof value === 'number' && value > def.max) fail(`> ${def.max}`);
|
|
88
|
+
if (typeof custom === 'function') {
|
|
89
|
+
const r = custom(value, row);
|
|
90
|
+
if (r === false) fail('custom validator failed');
|
|
91
|
+
if (typeof r === 'string') fail(r);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function createValidation(opts = {}) {
|
|
96
|
+
const validators = opts.validators || {};
|
|
97
|
+
// install 时拿到插件上下文(schema 查询),供各钩子闭包使用
|
|
98
|
+
let engineCtx = null;
|
|
99
|
+
|
|
100
|
+
const validateRow = (table, row, partial) => {
|
|
101
|
+
const schema = engineCtx && engineCtx.getTableSchema(table);
|
|
102
|
+
if (!schema) return;
|
|
103
|
+
const tableValidators = validators[table] || {};
|
|
104
|
+
for (const [field, rawDef] of Object.entries(schema)) {
|
|
105
|
+
const def = normalizeFieldDef(rawDef);
|
|
106
|
+
if (partial && !(field in row)) continue;
|
|
107
|
+
checkValue(table, field, def, row[field], row, tableValidators[field] || validators[field]);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const validateMany = (table, rows, partial) => {
|
|
112
|
+
if (Array.isArray(rows)) rows.forEach(r => validateRow(table, r, partial));
|
|
113
|
+
else if (rows && typeof rows === 'object') validateRow(table, rows, partial);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
return definePlugin('validation', {
|
|
117
|
+
install(engine, ctx) { engineCtx = ctx; },
|
|
118
|
+
hooks: {
|
|
119
|
+
beforeInsert(table, rows) { validateMany(table, rows, false); },
|
|
120
|
+
beforeUpdate(table, second, third) {
|
|
121
|
+
if (third !== undefined) { validateMany(table, third, true); return; }
|
|
122
|
+
if (Array.isArray(second)) for (const p of second) if (Array.isArray(p)) validateMany(table, p[1], true);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
module.exports = { createValidation, validation: createValidation };
|