jsql-neo 6.8.6 → 6.8.8

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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  > **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
4
4
  > MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
5
5
 
6
- > **v6.8.6** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
6
+ > **v6.8.8** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
7
7
 
8
8
  ![Engines](https://img.shields.io/badge/engines-Native%20%7C%20WASM%20%7C%20Pure%20JS-7ee787)
9
9
  ![MySQL](https://img.shields.io/badge/protocol-MySQL%20compatible-1f6feb)
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * JSQL-NEO v6.8.6 — Rust-Powered Embedded Database (WASM + HTTP)
2
+ * JSQL-NEO v6.8.8 — Rust-Powered Embedded Database (WASM + HTTP)
3
3
  *
4
4
  * @example
5
5
  * const jsql = require('jsql-neo');
package/lib/cache.js CHANGED
@@ -41,6 +41,12 @@ class Cache {
41
41
  const p = String(pattern);
42
42
  for (let i = 0; i < p.length; i++) {
43
43
  const c = p[i];
44
+ // #241:反斜杠转义下一个字符,按字面量匹配
45
+ if (c === '\\' && i + 1 < p.length) {
46
+ i++;
47
+ src += p[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
48
+ continue;
49
+ }
44
50
  if (c === '*') { src += '.*'; continue; }
45
51
  if (c === '?') { src += '.'; continue; }
46
52
  if (c === '[') {
package/lib/date-types.js CHANGED
@@ -49,6 +49,13 @@ function validateDateType(value, type, fieldName) {
49
49
 
50
50
  function pad2(n) { return String(n).padStart(2, '0'); }
51
51
 
52
+ // #239:Date.UTC 把 0-99 年当成 1900+y,显式 setUTCFullYear 才能支持 0001-0099
53
+ function utcDate(y, mo, day, h = 0, mi = 0, sec = 0, ms = 0) {
54
+ const d = new Date(Date.UTC(2000, mo, day, h, mi, sec, ms));
55
+ d.setUTCFullYear(y);
56
+ return d;
57
+ }
58
+
52
59
  /**
53
60
  * 解析 ISO-8601 字符串尾部残余部分里的时区标记,返回「相对 UTC 的分钟偏移」。
54
61
  * 输入形如 'Z'、'z'、'+08:00'、'-0500'、'.500Z'、' +02:00'。
@@ -109,7 +116,7 @@ function parseToUtcMs(str) {
109
116
  // 「溢出归一」行为(→ 3 月 1 日),与改动前 new Date(...) 的宽松解析一致。
110
117
  if (mo < 1 || mo > 12 || day < 1 || day > 31) return null;
111
118
  if (h > 23 || mi > 59 || sec > 59) return null;
112
- let ms = Date.UTC(y, mo - 1, day, h, mi, sec, frac);
119
+ let ms = utcDate(y, mo - 1, day, h, mi, sec, frac).getTime();
113
120
  const rest = m[8] === undefined ? '' : m[8];
114
121
  if (rest !== '') {
115
122
  const tz = parseIsoTimezone(rest);
@@ -139,7 +146,7 @@ function validateDate(value, fieldName) {
139
146
  if (/^\d{4}-\d{2}-\d{2}$/.test(s)) {
140
147
  const m = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
141
148
  const y = parseInt(m[1]), mo = parseInt(m[2]), d = parseInt(m[3]);
142
- const dt = new Date(Date.UTC(y, mo - 1, d));
149
+ const dt = utcDate(y, mo - 1, d);
143
150
  if (dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d) return s;
144
151
  }
145
152
  const d = parseDateString(s);
@@ -154,21 +161,21 @@ function parseDateString(str) {
154
161
  let m = str.match(/^(\d{4})-(\d{2})-(\d{2})$/);
155
162
  if (m) {
156
163
  const y = parseInt(m[1]), mo = parseInt(m[2]), d = parseInt(m[3]);
157
- const dt = new Date(Date.UTC(y, mo - 1, d));
164
+ const dt = utcDate(y, mo - 1, d);
158
165
  if (dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d) return dt;
159
166
  }
160
167
  // YYYY/MM/DD
161
168
  m = str.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);
162
169
  if (m) {
163
170
  const y = parseInt(m[1]), mo = parseInt(m[2]), d = parseInt(m[3]);
164
- const dt = new Date(Date.UTC(y, mo - 1, d));
171
+ const dt = utcDate(y, mo - 1, d);
165
172
  if (dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d) return dt;
166
173
  }
167
174
  // MM/DD/YYYY
168
175
  m = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
169
176
  if (m) {
170
177
  const y = parseInt(m[3]), mo = parseInt(m[1]), d = parseInt(m[2]);
171
- const dt = new Date(Date.UTC(y, mo - 1, d));
178
+ const dt = utcDate(y, mo - 1, d);
172
179
  if (dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d) return dt;
173
180
  }
174
181
  // 通用路径:自己解析部件 + 时区标记;不回落 new Date(str)(那会用本地时区)
@@ -213,7 +220,7 @@ function validateDateTime(value, fieldName) {
213
220
  if (dm && tm) {
214
221
  const y = parseInt(dm[1]), mo = parseInt(dm[2]), d = parseInt(dm[3]);
215
222
  const h = parseInt(tm[1]), mi = parseInt(tm[2]), s = parseInt(tm[3]);
216
- const dt = new Date(Date.UTC(y, mo - 1, d));
223
+ const dt = utcDate(y, mo - 1, d);
217
224
  if (dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d &&
218
225
  h >= 0 && h < 24 && mi >= 0 && mi < 60 && s >= 0 && s < 60) {
219
226
  // 带 Z / ±HH:MM 时区标记:先换算成绝对时刻,再以 UTC 墙上时间落库。
@@ -221,7 +228,7 @@ function validateDateTime(value, fieldName) {
221
228
  // 二者因此在 UTC 字面量上完全等价(#75 round-trip)。
222
229
  const tz = parseIsoTimezone(value.slice(isoMatch[0].length));
223
230
  if (tz !== null) {
224
- const ms = Date.UTC(y, mo - 1, d, h, mi, s) + msPart - tz * 60000;
231
+ const ms = utcDate(y, mo - 1, d, h, mi, s).getTime() + msPart - tz * 60000;
225
232
  return toUtcDateTimeStringMs(new Date(ms));
226
233
  }
227
234
  return datePart + ' ' + timePart + (msPart ? '.' + String(msPart).padStart(3, '0') : '');
@@ -239,7 +246,7 @@ function validateDateTime(value, fieldName) {
239
246
  if (dm && tm) {
240
247
  const y = parseInt(dm[1]), mo = parseInt(dm[2]), d = parseInt(dm[3]);
241
248
  const h = parseInt(tm[1]), mi = parseInt(tm[2]), s = parseInt(tm[3]);
242
- const dt = new Date(Date.UTC(y, mo - 1, d));
249
+ const dt = utcDate(y, mo - 1, d);
243
250
  if (dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d &&
244
251
  h >= 0 && h < 24 && mi >= 0 && mi < 60 && s >= 0 && s < 60) {
245
252
  return value; // 无时区 → 即 UTC 墙上时间,原样落库
@@ -340,13 +347,14 @@ function formatDate(value, format = 'YYYY-MM-DD') {
340
347
  if (isNaN(d.getTime())) return String(value);
341
348
 
342
349
  const pad = n => String(n).padStart(2, '0');
343
- return format
344
- .replace('YYYY', d.getUTCFullYear())
345
- .replace('MM', pad(d.getUTCMonth() + 1))
346
- .replace('DD', pad(d.getUTCDate()))
347
- .replace('HH', pad(d.getUTCHours()))
348
- .replace('mm', pad(d.getUTCMinutes()))
349
- .replace('ss', pad(d.getUTCSeconds()));
350
+ // #238:同一个 token 可能出现多次,必须全局替换
351
+ return String(format)
352
+ .replace(/YYYY/g, String(d.getUTCFullYear()).padStart(4, '0'))
353
+ .replace(/MM/g, pad(d.getUTCMonth() + 1))
354
+ .replace(/DD/g, pad(d.getUTCDate()))
355
+ .replace(/HH/g, pad(d.getUTCHours()))
356
+ .replace(/mm/g, pad(d.getUTCMinutes()))
357
+ .replace(/ss/g, pad(d.getUTCSeconds()));
350
358
  }
351
359
 
352
360
  module.exports = { validateDateType, now, formatDate };
package/lib/migrate.js CHANGED
@@ -39,14 +39,16 @@ function normalizeSchema(schema) {
39
39
  }
40
40
 
41
41
  function serializeValue(v) {
42
- // #235:NULL 与空串必须可区分(MySQL 约定 NULL 写 \N)
42
+ // #235:NULL 与空串必须可区分(MySQL 约定 NULL 写 \N);字面量 \N 反向转义
43
43
  if (v === null || v === undefined) return '\\N';
44
+ if (v === '\\N') return '\\\\N';
44
45
  if (v instanceof Date) return v.toISOString();
45
46
  if (typeof v === 'object') return JSON.stringify(v);
46
47
  return String(v);
47
48
  }
48
49
 
49
50
  function parseValue(str, type) {
51
+ if (str === '\\\\N') return '\\N'; // 字面量 \N 的转义形式
50
52
  if (str === '\\N') return null; // #235:显式 NULL 标记
51
53
  if (str === null || str === undefined) return null;
52
54
  const t = String(type || 'string').toLowerCase();
@@ -77,6 +79,8 @@ function parseCSV(text, opts = {}) {
77
79
  if (typeof text !== 'string') {
78
80
  throw new Error('parseCSV: csv must be a string');
79
81
  }
82
+ // 带 BOM 的 UTF-8 文件:去掉 BOM,否则首列表头会变成 \uFEFFid
83
+ if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
80
84
  const maxLen = opts.maxInputSize == null ? DEFAULT_MAX_CSV_LENGTH : opts.maxInputSize;
81
85
  if (typeof maxLen === 'number' && Number.isFinite(maxLen) && text.length > maxLen) {
82
86
  throw new Error(
@@ -1054,6 +1054,7 @@ class MongoServer {
1054
1054
  applyModifier(doc, updateDoc, { strict: true });
1055
1055
  // updateByIds 是 Object.assign 合并:被 $unset 删除的顶层字段需显式置 undefined
1056
1056
  for (const k of Object.keys(r)) if (!(k in doc)) doc[k] = undefined;
1057
+ this._checkUniqueIndexes(engine, coll, doc, r);
1057
1058
  entries.push([key, doc]);
1058
1059
  }
1059
1060
  if (entries.length > 0) {
@@ -1077,6 +1078,7 @@ class MongoServer {
1077
1078
  if (key === undefined) continue;
1078
1079
  const d = cloneDoc(replacement || {});
1079
1080
  if (r._id !== undefined) d._id = r._id;
1081
+ this._checkUniqueIndexes(engine, coll, d, r);
1080
1082
  ids.push(key);
1081
1083
  docs.push(d);
1082
1084
  }
@@ -1091,6 +1093,29 @@ class MongoServer {
1091
1093
  return out;
1092
1094
  }
1093
1095
 
1096
+ /** #221:写入/更新前按二级唯一索引查重 */
1097
+ _checkUniqueIndexes(engine, coll, doc, excludeRow) {
1098
+ let defs = [];
1099
+ for (const [key, list] of this._indexesByColl) {
1100
+ if (key.endsWith('.' + coll)) defs = defs.concat(list.filter(ix => ix.unique && ix.name !== '_id_'));
1101
+ }
1102
+ if (defs.length === 0) return;
1103
+ const table = engine && engine._tables && engine._tables[coll];
1104
+ if (!table || !Array.isArray(table._rows)) return;
1105
+ for (const ix of defs) {
1106
+ if (ix.columns.some(c => getPath(doc, c) === undefined || getPath(doc, c) === null)) continue;
1107
+ for (const row of table._rows) {
1108
+ if (row === excludeRow) continue;
1109
+ if (ix.columns.every(c => deepEqualMongo(getPath(row, c), getPath(doc, c)))) {
1110
+ const err = new Error(`E11000 duplicate key error collection: ${coll} index: ${ix.name} dup key: ${JSON.stringify(Object.fromEntries(ix.columns.map(c => [c, getPath(doc, c)])))}`);
1111
+ err.code = 11000;
1112
+ err.keyPattern = Object.fromEntries(ix.columns.map(c => [c, 1]));
1113
+ throw err;
1114
+ }
1115
+ }
1116
+ }
1117
+ }
1118
+
1094
1119
  async _removeRows(engine, coll, rows) {
1095
1120
  // 收集所有需要删除的行的 id,走 engine.removeByIds
1096
1121
  // 这样会写 WAL、触发 hooks、检查约束
package/lib/pg_server.js CHANGED
@@ -690,14 +690,14 @@ class PgConnection {
690
690
  this._send(buildReadyForQuery(this._rfqStatus()));
691
691
  return;
692
692
  }
693
- if (trimmed.startsWith('SET ')) {
694
- this._send(buildCommandComplete('SET'));
693
+ // aborted 事务里除 ROLLBACK/COMMIT 外一律拒绝(SET 也不能绕过)
694
+ if (this._txAborted && !/^(ROLLBACK|COMMIT)\b/i.test(trimmed)) {
695
+ this._send(buildErrorResponse('25P02', 'current transaction is aborted, commands ignored until end of transaction block'));
695
696
  this._send(buildReadyForQuery(this._rfqStatus()));
696
697
  return;
697
698
  }
698
- // #213:事务已 aborted 时,除 ROLLBACK/COMMIT 外的命令一律 25P02
699
- if (this._txAborted && !/^(ROLLBACK|COMMIT)\b/i.test(trimmed)) {
700
- this._send(buildErrorResponse('25P02', 'current transaction is aborted, commands ignored until end of transaction block'));
699
+ if (trimmed.startsWith('SET ')) {
700
+ this._send(buildCommandComplete('SET'));
701
701
  this._send(buildReadyForQuery(this._rfqStatus()));
702
702
  return;
703
703
  }
@@ -45,6 +45,12 @@ function globToRegex(pattern) {
45
45
  let src = '^';
46
46
  for (let i = 0; i < p.length; i++) {
47
47
  const c = p[i];
48
+ // #241:反斜杠转义下一个字符,按字面量匹配
49
+ if (c === '\\' && i + 1 < p.length) {
50
+ i++;
51
+ src += p[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
52
+ continue;
53
+ }
48
54
  if (c === '*') { src += '.*'; continue; }
49
55
  if (c === '?') { src += '.'; continue; }
50
56
  if (c === '[') {
@@ -67,11 +73,15 @@ function globToRegex(pattern) {
67
73
  const BIN_PREFIX = '\u0001';
68
74
  function decodeBulk(buf) {
69
75
  const s = buf.toString('utf8');
70
- if (Buffer.from(s, 'utf8').equals(buf)) return s;
76
+ if (Buffer.from(s, 'utf8').equals(buf)) {
77
+ // 合法文本恰好以保留前缀开头时再加一层前缀,回包时还原
78
+ return s.startsWith(BIN_PREFIX) ? BIN_PREFIX + BIN_PREFIX + s : s;
79
+ }
71
80
  return BIN_PREFIX + buf.toString('latin1');
72
81
  }
73
82
  function bulkToBuffer(v) {
74
83
  const s = String(v);
84
+ if (s.startsWith(BIN_PREFIX + BIN_PREFIX)) return Buffer.from(s.slice(BIN_PREFIX.length * 2), 'utf8');
75
85
  if (s.startsWith(BIN_PREFIX)) return Buffer.from(s.slice(BIN_PREFIX.length), 'latin1');
76
86
  return Buffer.from(s, 'utf8');
77
87
  }
package/lib/sql.js CHANGED
@@ -10309,7 +10309,23 @@ async function inferColumnTypes(engine, stmt, r) {
10309
10309
  ? stmt.from.tables[0].table : null;
10310
10310
  if (t && engine && typeof engine.getTableSchema === 'function') schema = await engine.getTableSchema(t);
10311
10311
  } catch (e) { schema = null; }
10312
+ const defs = (stmt && Array.isArray(stmt.columns)) ? stmt.columns : [];
10313
+ const aggType = (fn) => String(fn).toUpperCase() === 'COUNT' ? 'INT' : 'FLOAT';
10312
10314
  return r.columns.map((name) => {
10315
+ // #240:先按输出列找到对应表达式;聚合列按聚合函数类型,不能拿别名回查表列
10316
+ const c = defs.find((d) => scalarColumnName(d) === name);
10317
+ if (c) {
10318
+ if (c.aggregate) return aggType(c.aggregate);
10319
+ if (c.scalar && containsAggregateNode(c.scalar)) return 'FLOAT';
10320
+ if (c.scalar && c.scalar.type === 'column' && schema && schema[c.scalar.name]) {
10321
+ return sqlTypeName(schema[c.scalar.name].type).toUpperCase();
10322
+ }
10323
+ if (typeof c.expr === 'string' && c.expr !== '*' && (!c.alias || c.alias === c.expr)) {
10324
+ const def = schema && schema[c.expr];
10325
+ if (def && def.type) return sqlTypeName(def.type).toUpperCase();
10326
+ }
10327
+ return null;
10328
+ }
10313
10329
  const def = schema && schema[name];
10314
10330
  return def && def.type ? sqlTypeName(def.type).toUpperCase() : null;
10315
10331
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsql-neo",
3
- "version": "6.8.6",
3
+ "version": "6.8.8",
4
4
  "description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -52,12 +52,12 @@
52
52
  "build:native": "node scripts/build-native.js",
53
53
  "check:release": "node scripts/check-release-metadata.js",
54
54
  "release:prep": "node scripts/release.js",
55
- "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js",
55
+ "test": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js",
56
56
  "test:parser": "node test/sql-parser.test.js",
57
57
  "test:btree": "node test/btree.test.js",
58
58
  "test:native": "node test/native.test.js",
59
59
  "test:regress": "node test/regress-5.1.0.js",
60
- "test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js",
60
+ "test:all": "npm run check:release && node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js && node test/issue-101-103.test.js && node test/issue-105.test.js && node test/issue-118-136.test.js && node test/issue-127.test.js && node test/issue-138-156.test.js && node test/issue-157-161.test.js && node test/issue-162-179.test.js && node test/issue-181-186.test.js && node test/issue-187.test.js && node test/issue-188-237.test.js && node test/issue-238-241.test.js && node test/bigint-math.test.js && node test/release-metadata.test.js && node test/date-conversions.test.js && node test/mysql-utility-functions.test.js && node test/limit-pushdown.test.js && node test/columnar.test.js && node test/columnar-vector.test.js && node test/cast-rounding.test.js && node test/convert-subquery.test.js && node test/mongo-persistence.test.js && node test/mongo-objectid.test.js && node test/mongo-arrays.test.js && node test/issue-117.test.js",
61
61
  "test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
62
62
  "test:orms": "node examples/orms/run-all.js",
63
63
  "test:dml": "node test/dml-constraints.test.js",
@@ -0,0 +1,144 @@
1
+ /*
2
+ * Regression tests for issues #238-#241.
3
+ * node test/issue-238-241.test.js
4
+ */
5
+ const path = require('path');
6
+ const ROOT = path.join(__dirname, '..');
7
+ const { formatDate, validateDateType } = require(path.join(ROOT, 'lib', 'date-types.js'));
8
+ const Cache = require(path.join(ROOT, 'lib', 'cache.js'));
9
+ const { JSQL } = require(path.join(ROOT, 'index.js'));
10
+
11
+ let passed = 0, failed = 0;
12
+ function ok(name, cond, extra) {
13
+ if (cond) { passed++; console.log('[OK]', name); }
14
+ else { failed++; console.log('[FAIL]', name, extra !== undefined ? '→ ' + JSON.stringify(extra) : ''); }
15
+ }
16
+
17
+ (async () => {
18
+ // #238
19
+ const f1 = formatDate('2024-01-02 13:45:59', 'YYYY-MM-DD HH:mm:ss HH');
20
+ const f2 = formatDate('2024-01-02', 'YYYY YYYY');
21
+ ok('#238 repeated format tokens all replaced', f1 === '2024-01-02 13:45:59 13' && f2 === '2024 2024', { f1, f2 });
22
+
23
+ // #239
24
+ const dates = ['0099-01-02', '0050-06-15', '0001-12-31'];
25
+ let allOk = true;
26
+ for (const s of dates) {
27
+ try { if (validateDateType(s, 'date', 'd') !== s) allOk = false; } catch (e) { allOk = false; }
28
+ }
29
+ ok('#239 years 0001-0099 are valid', allOk);
30
+ ok('#239 formatDate keeps low year', formatDate('0099-01-02', 'YYYY') === '0099', formatDate('0099-01-02', 'YYYY'));
31
+
32
+ // #241
33
+ {
34
+ const c = new Cache();
35
+ ['a*', 'ab', 'a?'].forEach(k => c.set(k, 1));
36
+ const star = c.keys('a\\*');
37
+ const qm = c.keys('a\\?');
38
+ ok('#241 Cache.keys glob backslash escape', JSON.stringify(star) === JSON.stringify(['a*']) && JSON.stringify(qm) === JSON.stringify(['a?']), { star, qm });
39
+ c.close();
40
+ }
41
+
42
+ // CSV literal \\N must not collapse to NULL
43
+ {
44
+ const fs = require('fs');
45
+ const os = require('os');
46
+ const { Database, migrate } = require(path.join(ROOT, 'index.js'));
47
+ const db = new Database(':memory:');
48
+ await db.query('CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT)', { safety: false });
49
+ await db.query("INSERT INTO t VALUES (1,'\\\\N'),(2,NULL)", { safety: false });
50
+ const csv = await migrate.exportTableToCSV(db, 't');
51
+ const db2 = new Database(':memory:');
52
+ await db2.query('CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT)', { safety: false });
53
+ await migrate.importFromCSV(db2, 't', csv);
54
+ const r = (await db2.query('SELECT * FROM t ORDER BY id', { safety: false })).rows;
55
+ ok('CSV literal \\N round-trips without becoming NULL', JSON.stringify(r) === JSON.stringify([[1, '\\N'], [2, null]]), r);
56
+ db.stop(); db2.stop();
57
+ }
58
+
59
+ // PG aborted transaction also rejects SET
60
+ {
61
+ const { Client } = (() => { try { return require(path.join(ROOT, 'node_modules', 'pg')); } catch (e) { return {}; } })();
62
+ if (Client) {
63
+ const { createPgServer } = require(path.join(ROOT, 'lib', 'pg_server.js'));
64
+ const srv = createPgServer({ port: 0, host: '127.0.0.1', dataDir: ':memory:', noAuth: true });
65
+ await new Promise((r) => srv.listen(r));
66
+ const c = new Client({ host: '127.0.0.1', port: srv.address.port, user: 'root', database: 'app' });
67
+ await c.connect();
68
+ await c.query('BEGIN');
69
+ try { await c.query('SELECT * FROM no_such_table'); } catch (e) { /* aborted */ }
70
+ let code = null;
71
+ try { await c.query('SET search_path=foo'); } catch (e) { code = e.code; }
72
+ ok('PG aborted transaction rejects SET too', code === '25P02', code);
73
+ await c.query('ROLLBACK');
74
+ await c.end(); srv.close();
75
+ } else {
76
+ console.log('[SKIP] PG aborted SET (pg not installed)');
77
+ }
78
+ }
79
+
80
+ // CSV BOM header
81
+ {
82
+ const { Database, migrate } = require(path.join(ROOT, 'index.js'));
83
+ const db = new Database(':memory:');
84
+ await db.query('CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT)', { safety: false });
85
+ await migrate.importFromCSV(db, 't', '\uFEFFid,s\n1,hi\n');
86
+ const r = (await db.query('SELECT * FROM t', { safety: false })).rows;
87
+ ok('CSV BOM header is stripped', JSON.stringify(r) === JSON.stringify([[1, 'hi']]), r);
88
+ db.stop();
89
+ }
90
+
91
+ // Redis valid text starting with the binary marker must round-trip
92
+ {
93
+ const net = require('net');
94
+ const { createRedisServer } = require(path.join(ROOT, 'lib', 'redis_server.js'));
95
+ const srv = createRedisServer({ port: 0, dataDir: null });
96
+ await new Promise((r) => srv.listen(r));
97
+ const sock = net.connect(srv.server.address().port, '127.0.0.1');
98
+ await new Promise((r) => sock.on('connect', r));
99
+ const chunks = [];
100
+ sock.on('data', (c) => chunks.push(c));
101
+ const val = Buffer.from('\u0001hello', 'utf8');
102
+ sock.write(Buffer.concat([Buffer.from('*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$' + val.length + '\r\n'), val, Buffer.from('\r\n')]));
103
+ sock.write(Buffer.from('*2\r\n$3\r\nGET\r\n$1\r\nk\r\n'));
104
+ await new Promise((r) => setTimeout(r, 120));
105
+ const out = Buffer.concat(chunks);
106
+ const at = out.indexOf('$' + val.length + '\r\n');
107
+ ok('Redis leading \\u0001 text is not treated as binary', at >= 0 && out.slice(at + 3 + String(val.length).length, at + 3 + String(val.length).length + val.length).equals(val), out.toString('hex'));
108
+ sock.end(); srv.stop();
109
+ }
110
+
111
+ // Mongo unique index must also block UPDATE to a duplicate key
112
+ {
113
+ const { createMongoServer } = require(path.join(ROOT, 'lib', 'mongo_server.js'));
114
+ const mongo = createMongoServer({ dataDir: ':memory:' });
115
+ await mongo._dispatch('createIndexes', { createIndexes: 'c', indexes: [{ key: { email: 1 }, name: 'email_1', unique: true }], $db: 'test' });
116
+ await mongo._dispatch('insert', { insert: 'c', documents: [{ email: 'a@x.com' }, { email: 'b@x.com' }], $db: 'test' });
117
+ const upd = await mongo._dispatch('update', { update: 'c', updates: [{ q: { email: 'b@x.com' }, u: { $set: { email: 'a@x.com' } } }], $db: 'test' });
118
+ ok('Mongo unique index enforced on UPDATE', upd.ok === 0, upd);
119
+ }
120
+
121
+ // #240
122
+ {
123
+ const db = new JSQL();
124
+ await db.start();
125
+ await db.createTable('t', {
126
+ id: { type: 'integer', primaryKey: true },
127
+ v: { type: 'integer' },
128
+ s: { type: 'string' },
129
+ });
130
+ await db.insert('t', { id: 1, v: 10, s: 'aa' });
131
+ await db.insert('t', { id: 2, v: 20, s: 'bb' });
132
+ const sum = await db.query('SELECT SUM(v) AS s FROM t');
133
+ const avg = await db.query('SELECT AVG(v) AS v FROM t');
134
+ const count = await db.query('SELECT COUNT(*) AS c FROM t');
135
+ const plain = await db.query('SELECT s FROM t');
136
+ ok('#240 aggregate column types do not use alias', sum.columnTypes[0] !== 'VARCHAR(255)' && avg.columnTypes[0] !== 'INT', { sum: sum.columnTypes, avg: avg.columnTypes });
137
+ ok('#240 COUNT is INT', count.columnTypes[0] === 'INT', count.columnTypes);
138
+ ok('#240 plain string column type', plain.columnTypes[0] === 'VARCHAR(255)', plain.columnTypes);
139
+ await db.stop();
140
+ }
141
+
142
+ console.log(`\n${passed} passed, ${failed} failed`);
143
+ process.exit(failed === 0 ? 0 : 1);
144
+ })().catch((e) => { console.error('FATAL', e); process.exit(1); });