jsql-neo 6.8.4 → 6.8.7

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.
@@ -315,6 +315,37 @@ class Datastore {
315
315
  this.database = options.database || options.engine || null;
316
316
  this._ownEngine = false;
317
317
  this._started = false;
318
+ this._indexes = []; // #193:ensureIndex 登记的索引(含 unique 约束)
319
+ }
320
+
321
+ _uniqueFields() {
322
+ const out = ['_id'];
323
+ for (const ix of this._indexes || []) if (ix && ix.unique && ix.fieldName) out.push(ix.fieldName);
324
+ return [...new Set(out)];
325
+ }
326
+
327
+ _uniqueError(field, value) {
328
+ const e = new Error(`Unique constraint violated for key ${field}`);
329
+ e.errorType = 'uniqueViolated';
330
+ e.key = field;
331
+ e.value = value;
332
+ return e;
333
+ }
334
+
335
+ /** 检查 doc 在 unique 字段上是否与 docs(排除 excludeDoc)冲突 */
336
+ _assertUnique(doc, docs, excludeDoc) {
337
+ for (const f of this._uniqueFields()) {
338
+ const v = getPath(doc, f);
339
+ if (v === undefined || v === null) continue;
340
+ const key = JSON.stringify(v);
341
+ for (const other of docs) {
342
+ if (!other || other === excludeDoc || other === doc) continue;
343
+ const ov = getPath(other, f);
344
+ if (ov !== undefined && ov !== null && JSON.stringify(ov) === key) {
345
+ throw this._uniqueError(f, v);
346
+ }
347
+ }
348
+ }
318
349
  }
319
350
 
320
351
  async _ensureEngine() {
@@ -369,9 +400,31 @@ class Datastore {
369
400
  this._lastInserted = doc;
370
401
  return { _doc: JSON.stringify(doc) };
371
402
  });
403
+ // #190 / #193:显式 _id 与 unique 索引字段在写入前查重(整批原子)
404
+ const uniqueFields = this._uniqueFields();
405
+ const existing = await this._readDocs();
406
+ const seen = new Map();
407
+ for (const f of uniqueFields) {
408
+ const set = new Set();
409
+ for (const { doc } of existing) {
410
+ const v = getPath(doc, f);
411
+ if (v !== undefined && v !== null) set.add(JSON.stringify(v));
412
+ }
413
+ seen.set(f, set);
414
+ }
415
+ const insertedDocs = rows.map(r => JSON.parse(r._doc));
416
+ for (const doc of insertedDocs) {
417
+ for (const f of uniqueFields) {
418
+ const v = getPath(doc, f);
419
+ if (v === undefined || v === null) continue;
420
+ const k = JSON.stringify(v);
421
+ if (seen.get(f).has(k)) throw this._uniqueError(f, v);
422
+ seen.get(f).add(k);
423
+ }
424
+ }
372
425
  await db.insert(name, rows);
373
426
  await db.flush();
374
- const inserted = arr.map((d, i) => JSON.parse(rows[i]._doc));
427
+ const inserted = insertedDocs;
375
428
  return single ? inserted[0] : inserted;
376
429
  })();
377
430
  if (cb) p.then(r => cb(null, r), err => cb(err));
@@ -414,12 +467,27 @@ class Datastore {
414
467
  if (opts.skip) docs = docs.slice(opts.skip);
415
468
  if (opts.limit !== null && opts.limit !== undefined) docs = docs.slice(0, opts.limit);
416
469
  if (opts.projection) {
470
+ const spec = opts.projection;
471
+ const keys = Object.keys(spec).filter(k => k !== '_id');
472
+ const includes = keys.filter(k => spec[k]);
473
+ const excludes = keys.filter(k => !spec[k]);
474
+ // #191:除 _id 外不能混用包含/排除
475
+ if (includes.length > 0 && excludes.length > 0) {
476
+ throw new Error('Cannot both keep and omit fields except for _id');
477
+ }
478
+ const includeMode = includes.length > 0;
417
479
  docs = docs.map(d => {
418
- const out = {};
419
- for (const [k, include] of Object.entries(opts.projection)) {
420
- if (include) out[k] = getPath(d, k);
480
+ if (includeMode) {
481
+ const out = {};
482
+ for (const k of includes) { const v = getPath(d, k); if (v !== undefined) setPath(out, k, v); }
483
+ if (d._id !== undefined && spec._id !== 0) out._id = d._id;
484
+ return out;
421
485
  }
422
- if (d._id !== undefined && opts.projection._id !== 0) out._id = d._id;
486
+ // 排除模式:先整体拷贝,再删除排除字段
487
+ const out = {};
488
+ for (const k of Object.keys(d)) out[k] = d[k];
489
+ for (const k of excludes) unsetPath(out, k);
490
+ if (spec._id === 0) delete out._id;
423
491
  return out;
424
492
  });
425
493
  }
@@ -452,18 +520,27 @@ class Datastore {
452
520
  const matched = entries.filter(({ doc }) => match(doc, query));
453
521
  let affected = 0;
454
522
  let upserted = null;
523
+ const updatedDocs = [];
455
524
  if (matched.length === 0 && opts.upsert) {
456
525
  const base = {};
457
526
  for (const [k, v] of Object.entries(query)) {
458
527
  if (!k.startsWith('$')) base[k] = v;
459
528
  }
460
- const newDoc = isModifier(update)
461
- ? { ...base, ...(update.$set || {}) }
462
- : { ...update };
529
+ // #194:upsert 必须应用全部修饰符,而不是只展开 $set
530
+ let newDoc;
531
+ if (isModifier(update)) {
532
+ newDoc = base;
533
+ applyModifier(newDoc, update);
534
+ } else {
535
+ newDoc = { ...update };
536
+ }
463
537
  if (newDoc._id === undefined) newDoc._id = genId();
538
+ this._assertUnique(newDoc, entries.map(e => e.doc), null);
464
539
  await db.insert(name, { _doc: JSON.stringify(newDoc) });
465
540
  await db.flush();
541
+ affected = 1;
466
542
  upserted = { ...newDoc };
543
+ updatedDocs.push(newDoc);
467
544
  } else {
468
545
  const targets = opts.multi ? matched : matched.slice(0, 1);
469
546
  const updates = [];
@@ -477,9 +554,12 @@ class Datastore {
477
554
  Object.assign(next, update);
478
555
  next._id = doc._id;
479
556
  }
557
+ // #193:UPDATE 也不能撞上 unique 字段
558
+ this._assertUnique(next, entries.map(e => e.doc), doc);
480
559
  if (JSON.stringify(next) !== JSON.stringify(doc)) {
481
560
  updates.push([id, { _doc: JSON.stringify(next) }]);
482
561
  affected++;
562
+ updatedDocs.push(next);
483
563
  }
484
564
  }
485
565
  if (updates.length > 0) {
@@ -492,8 +572,12 @@ class Datastore {
492
572
  }
493
573
  }
494
574
  if (opts.returnUpdatedDocs) {
495
- const docs = await this._findDocs(query, { limit: opts.multi ? 1e9 : 1 });
496
- return { numAffected: affected, affectedDocuments: docs, upsert: upserted };
575
+ // #192:非 multi 返回单个文档;未命中返回 null
576
+ let affectedDocuments;
577
+ if (upserted) affectedDocuments = upserted;
578
+ else if (opts.multi) affectedDocuments = updatedDocs;
579
+ else affectedDocuments = updatedDocs.length ? updatedDocs[0] : null;
580
+ return { numAffected: affected, affectedDocuments, upsert: upserted };
497
581
  }
498
582
  return affected;
499
583
  })();
@@ -529,7 +613,13 @@ class Datastore {
529
613
 
530
614
  async ensureIndex(options = {}) {
531
615
  await this._ensureEngine();
532
- return { fieldName: options.fieldName, unique: options.unique === true };
616
+ // #193:保存索引定义,insert/update 依此强制 unique
617
+ const ix = { fieldName: options.fieldName, unique: options.unique === true };
618
+ if (ix.fieldName) {
619
+ const at = this._indexes.findIndex(i => i.fieldName === ix.fieldName);
620
+ if (at >= 0) this._indexes[at] = ix; else this._indexes.push(ix);
621
+ }
622
+ return ix;
533
623
  }
534
624
 
535
625
  async compaction() {
package/lib/pg_server.js CHANGED
@@ -39,8 +39,17 @@ const TYPE_OIDS = {
39
39
  varchar: 1043, bpchar: 1042, uuid: 2950, serial: 23, bigserial: 20, name: 19
40
40
  };
41
41
 
42
+ function pgSchemaType(def) {
43
+ if (!def) return 'string';
44
+ if (def.intType === 'bigint') return 'bigint';
45
+ if (def.numericType === 'numeric') return 'numeric';
46
+ return def.type;
47
+ }
48
+
42
49
  function pgTypeOid(sqlType, def) {
43
50
  const t = String(sqlType || '').toLowerCase();
51
+ if (t === 'bigint') return 20; // int8
52
+ if (t === 'numeric' || t === 'decimal') return 1700;
44
53
  if (t === 'integer') return 23;
45
54
  if (t === 'number') return 701;
46
55
  if (t === 'boolean') return 16;
@@ -68,10 +77,21 @@ function pgFormatValue(value, sqlType) {
68
77
  return d.toISOString().slice(0, 10);
69
78
  }
70
79
  if (t === 'datetime' || t === 'timestamp') {
80
+ // #215:引擎 TIMESTAMP 存 Unix 秒;数值必须按秒还原,不能当毫秒
81
+ if (typeof value === 'number') {
82
+ const ms = value < 1e12 ? value * 1000 : value;
83
+ const d = new Date(ms);
84
+ if (isNaN(d.getTime())) return String(value);
85
+ return d.toISOString().replace('T', ' ').slice(0, 19);
86
+ }
87
+ // DATETIME 在引擎里是 'YYYY-MM-DD HH:MM:SS' 字符串,原样透传,不要二次换算时区
88
+ if (typeof value === 'string') return value;
71
89
  const d = value instanceof Date ? value : new Date(value);
72
90
  if (isNaN(d.getTime())) return String(value);
73
91
  return d.toISOString().replace('T', ' ').slice(0, 19);
74
92
  }
93
+ // #214:numeric 以十进制字符串下发,避免 double 二次舍入
94
+ if (t === 'numeric' || t === 'decimal') return String(value);
75
95
  if (typeof value === 'boolean') return value ? 't' : 'f';
76
96
  return String(value);
77
97
  }
@@ -140,7 +160,7 @@ function buildRowDescription(columns, types) {
140
160
  p.i32(0); // table oid
141
161
  p.i16(0); // column attnum
142
162
  p.i32(pgTypeOid(types[i]));
143
- p.i16(types[i] === 'integer' ? 4 : -1); // typlen
163
+ p.i16(types[i] === 'integer' ? 4 : (types[i] === 'bigint' ? 8 : -1)); // typlen
144
164
  p.i32(-1); // typmod
145
165
  p.i16(0); // format code (text)
146
166
  }
@@ -289,6 +309,7 @@ class PgConnection {
289
309
  this._prepared = new Map(); // name -> { sql, paramTypes }
290
310
  this._portal = new Map(); // name -> { values }
291
311
  this._inTransaction = false;
312
+ this._txAborted = false;
292
313
  this._txId = null;
293
314
  this._pid = 0;
294
315
  this._secret = 0;
@@ -364,7 +385,7 @@ class PgConnection {
364
385
  }
365
386
  } catch (e) {
366
387
  this._send(buildErrorResponse('XX000', e && e.message ? e.message : String(e)));
367
- this._send(buildReadyForQuery(this._inTransaction ? 'T' : 'I'));
388
+ this._send(buildReadyForQuery(this._rfqStatus()));
368
389
  }
369
390
  });
370
391
  }
@@ -553,7 +574,7 @@ class PgConnection {
553
574
  this._handleClose(body);
554
575
  break;
555
576
  case 0x53: // 'S' sync
556
- this._send(buildReadyForQuery(this._inTransaction ? 'T' : 'I'));
577
+ this._send(buildReadyForQuery(this._rfqStatus()));
557
578
  break;
558
579
  case 0x46: // 'F' function call
559
580
  this._send(buildErrorResponse('0A000', 'function call not supported'));
@@ -637,9 +658,10 @@ class PgConnection {
637
658
  if (c.scalar) {
638
659
  push(c.scalar.name, this._astType(c.scalar, schema));
639
660
  } else if (c.expr === '*') {
640
- for (const [name, def] of Object.entries(schema)) push(name, def.type);
661
+ for (const [name, def] of Object.entries(schema)) push(name, pgSchemaType(def));
641
662
  } else if (c.expr) {
642
- push(String(c.expr).includes('.') ? String(c.expr).slice(String(c.expr).lastIndexOf('.') + 1) : c.expr, schema[c.expr] ? schema[c.expr].type : 'string');
663
+ const nm = String(c.expr).includes('.') ? String(c.expr).slice(String(c.expr).lastIndexOf('.') + 1) : c.expr;
664
+ push(nm, schema[nm] ? pgSchemaType(schema[nm]) : 'string');
643
665
  }
644
666
  }
645
667
  return { columns, types };
@@ -650,7 +672,7 @@ class PgConnection {
650
672
 
651
673
  _astType(node, schema) {
652
674
  if (!node) return 'string';
653
- if (node.type === 'column') return schema[node.name] ? schema[node.name].type : 'string';
675
+ if (node.type === 'column') return schema[node.name] ? pgSchemaType(schema[node.name]) : 'string';
654
676
  if (node.type === 'cast') return String(node.to).includes('int') ? 'integer' : 'string';
655
677
  if (node.type === 'func') {
656
678
  const n = String(node.name).toUpperCase();
@@ -665,29 +687,41 @@ class PgConnection {
665
687
  const trimmed = sql.trim();
666
688
  if (!trimmed) {
667
689
  this._send(buildEmptyQuery());
668
- this._send(buildReadyForQuery(this._inTransaction ? 'T' : 'I'));
690
+ this._send(buildReadyForQuery(this._rfqStatus()));
669
691
  return;
670
692
  }
671
693
  if (trimmed.startsWith('SET ')) {
672
694
  this._send(buildCommandComplete('SET'));
673
- this._send(buildReadyForQuery(this._inTransaction ? 'T' : 'I'));
695
+ this._send(buildReadyForQuery(this._rfqStatus()));
696
+ return;
697
+ }
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'));
701
+ this._send(buildReadyForQuery(this._rfqStatus()));
674
702
  return;
675
703
  }
676
704
  try {
677
705
  await this._executeSql(sql, null);
678
706
  } catch (e) {
707
+ if (this._inTransaction) this._txAborted = true;
679
708
  this._send(buildErrorResponse(this._pgErrorCode(e), e && e.message ? e.message : String(e)));
680
- this._send(buildReadyForQuery(this._inTransaction ? 'T' : 'I'));
709
+ this._send(buildReadyForQuery(this._rfqStatus()));
681
710
  return;
682
711
  }
683
- this._send(buildReadyForQuery(this._inTransaction ? 'T' : 'I'));
712
+ this._send(buildReadyForQuery(this._rfqStatus()));
684
713
  }
685
714
 
686
715
  async _execute(portal) {
716
+ if (this._txAborted) {
717
+ this._send(buildErrorResponse('25P02', 'current transaction is aborted, commands ignored until end of transaction block'));
718
+ return;
719
+ }
687
720
  try {
688
721
  const { sql } = portal.stmt;
689
722
  await this._executeSql(sql, portal.values || []);
690
723
  } catch (e) {
724
+ if (this._inTransaction) this._txAborted = true;
691
725
  this._send(buildErrorResponse(this._pgErrorCode(e), e && e.message ? e.message : String(e)));
692
726
  }
693
727
  }
@@ -733,6 +767,7 @@ class PgConnection {
733
767
  this._send(buildCommandComplete(tag));
734
768
  } else if (res.type === 'begin' || res.type === 'commit' || res.type === 'rollback') {
735
769
  this._inTransaction = res.type === 'begin';
770
+ this._txAborted = false;
736
771
  this._send(buildCommandComplete(String(res.type).toUpperCase()));
737
772
  } else if (res.type === 'createTable' || res.type === 'dropTable' || res.type === 'createDatabase' || res.type === 'dropDatabase') {
738
773
  this._send(buildCommandComplete('OK'));
@@ -751,14 +786,20 @@ class PgConnection {
751
786
  try {
752
787
  const schema = this.server._tableSchema(this.database, res.table);
753
788
  if (schema) {
754
- for (const [name, def] of Object.entries(schema)) t[name] = def.type;
789
+ for (const [name, def] of Object.entries(schema)) t[name] = pgSchemaType(def);
755
790
  }
756
791
  } catch (e) {}
757
792
  return (res.columns || []).map(c => t[c] || 'string');
758
793
  }
759
794
 
760
- _pgErrorCode(e) {
795
+ _rfqStatus() {
796
+ // #213:aborted 事务态 'E'
797
+ return this._txAborted ? 'E' : (this._inTransaction ? 'T' : 'I');
798
+ }
799
+
800
+ _pgErrorCode(e) {
761
801
  if (!e) return 'XX000';
802
+ if (/current transaction is aborted/i.test(String(e.message || ''))) return '25P02';
762
803
  const codeKey = e.code;
763
804
  const m = String(e.message || '');
764
805
  // Map JSQL error keys to PG SQLSTATE codes