jsql-neo 6.8.25 → 6.8.26

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.
@@ -94,8 +94,18 @@ const CLIENT_MULTI_RESULTS = 0x00020000;
94
94
  const CLIENT_LONG_FLAG = 0x00000004;
95
95
  const CLIENT_DEPRECATE_EOF = 0x01000000;
96
96
  const SERVER_STATUS_AUTOCOMMIT = 0x0002;
97
+ const SERVER_STATUS_IN_TRANS = 0x0001; // #372
97
98
  const SERVER_MORE_RESULTS_EXISTS = 0x0008;
98
99
  const CHARSET_UTF8 = 0x2d; // #212: 45 = utf8mb4_general_ci(33 是 utf8mb3/cesu8)
100
+ const CHARSET_LATIN1 = 0x08; // latin1_swedish_ci
101
+ const PARAM_UNSIGNED_FLAG = 0x0020; // COM_STMT_EXECUTE 参数块 flags 高字节无符号位
102
+
103
+ // 会话字符集名 → 列定义通告的 collation/charsetNr(#393)
104
+ function charsetNrByName(name) {
105
+ const n = String(name || '').toLowerCase();
106
+ if (n === 'latin1') return CHARSET_LATIN1;
107
+ return CHARSET_UTF8;
108
+ }
99
109
 
100
110
  const MYSQL_TYPE_TINY = 1, MYSQL_TYPE_LONG = 3, MYSQL_TYPE_LONGLONG = 8,
101
111
  MYSQL_TYPE_DATE = 10, MYSQL_TYPE_DATETIME = 12, MYSQL_TYPE_DOUBLE = 5,
@@ -321,7 +331,7 @@ function columnTypeFromSchema(def) {
321
331
  return MYSQL_TYPE_VAR_STRING;
322
332
  }
323
333
 
324
- function resultSetPacket(result, tableSchema, baseSeq, rawRow, status = SERVER_STATUS_AUTOCOMMIT) {
334
+ function resultSetPacket(result, tableSchema, baseSeq, rawRow, status = SERVER_STATUS_AUTOCOMMIT, charsetNr = CHARSET_UTF8) {
325
335
  const packets = [];
326
336
  let sequence = baseSeq || 0;
327
337
  const push = (buf) => {
@@ -359,6 +369,7 @@ function resultSetPacket(result, tableSchema, baseSeq, rawRow, status = SERVER_S
359
369
  type: inferType(name, sample),
360
370
  flags: columnFlags(tableSchema && tableSchema[name]),
361
371
  length: 1024,
372
+ charset: charsetNr,
362
373
  };
363
374
  push(columnDefinition(col));
364
375
  }
@@ -385,7 +396,7 @@ function resultSetPacket(result, tableSchema, baseSeq, rawRow, status = SERVER_S
385
396
  return { packets, sequence };
386
397
  }
387
398
 
388
- function binaryResultSetPacket(result, tableSchema, baseSeq, status = SERVER_STATUS_AUTOCOMMIT) {
399
+ function binaryResultSetPacket(result, tableSchema, baseSeq, status = SERVER_STATUS_AUTOCOMMIT, charsetNr = CHARSET_UTF8) {
389
400
  const packets = [];
390
401
  let sequence = baseSeq || 0;
391
402
  const push = (buf) => {
@@ -418,7 +429,7 @@ function binaryResultSetPacket(result, tableSchema, baseSeq, status = SERVER_STA
418
429
  }
419
430
  const t = inferType(cols[ci], sample);
420
431
  types.push(t);
421
- push(columnDefinition({ name: String(cols[ci]), table: result.table || '', database: result.database || '', type: t, flags: columnFlags(tableSchema && tableSchema[cols[ci]]), length: 1024 }));
432
+ push(columnDefinition({ name: String(cols[ci]), table: result.table || '', database: result.database || '', type: t, flags: columnFlags(tableSchema && tableSchema[cols[ci]]), length: 1024, charset: charsetNr }));
422
433
  }
423
434
  push(eofPacket(status));
424
435
 
@@ -506,6 +517,8 @@ class MysqlConnection {
506
517
  this.user = null;
507
518
  this.authFails = 0;
508
519
  this.multiStatements = false;
520
+ // #372:BEGIN/COMMIT 后状态位从不置 IN_TRANS,客户端无法判断是否处于事务
521
+ this._inTransaction = false;
509
522
  this._stmts = new Map();
510
523
  this._stmtSeq = 0;
511
524
  this.session = {
@@ -515,6 +528,8 @@ class MysqlConnection {
515
528
  connectionId: server._connectionCounter,
516
529
  currentDb: null,
517
530
  sysvars: {},
531
+ charset: 'utf8mb4',
532
+ charsetNr: CHARSET_UTF8,
518
533
  };
519
534
  if (server.handshakeTimeout > 0) {
520
535
  this._authTimer = setTimeout(() => {
@@ -618,9 +633,9 @@ class MysqlConnection {
618
633
  case 0x1f: this._send(okPacket()); break; // COM_RESET_CONNECTION
619
634
  case 0x16: this._handleStmtPrepare(body); break; // COM_STMT_PREPARE
620
635
  case 0x17: this._handleStmtExecute(body); break; // COM_STMT_EXECUTE
621
- case 0x18: break; // COM_STMT_SEND_LONG_DATA (忽略)
636
+ case 0x18: this._handleStmtSendLongData(body); break; // COM_STMT_SEND_LONG_DATA
622
637
  case 0x19: this._handleStmtClose(body); break; // COM_STMT_CLOSE
623
- case 0x1a: this._send(okPacket()); break; // COM_STMT_RESET
638
+ case 0x1a: this._handleStmtReset(body); break; // COM_STMT_RESET
624
639
  case 0x0a: { // COM_PROCESS_INFO
625
640
  const seq = this.sequence;
626
641
  this.sequence = (this.sequence + 1) & 0xff;
@@ -712,6 +727,8 @@ class MysqlConnection {
712
727
  try {
713
728
  const caps = payload.readUInt32LE(0);
714
729
  let pos = 32; // 4 caps + 4 maxpacket + 1 charset + 23 reserved
730
+ // #393:登录包字符集字节(偏移 8)记入会话,作为初始结果集 charsetNr
731
+ if (payload.length > 8) this.session.charsetNr = payload[8] || CHARSET_UTF8;
715
732
  const userEnd = payload.indexOf(0, pos);
716
733
  this.user = payload.slice(pos, userEnd).toString('utf8');
717
734
  pos = userEnd + 1;
@@ -763,7 +780,12 @@ class MysqlConnection {
763
780
  return;
764
781
  }
765
782
  try {
766
- if (!this.server._dbExists(db)) await this.server.createDatabase(db);
783
+ // #394:握手指定的库不存在时回 1049 Unknown database,不再隐式建库(与 COM_INIT_DB 一致)
784
+ if (!this.server._dbExists(db)) {
785
+ this._send(errPacket(1049, `Unknown database '${db}'`));
786
+ this.socket.end();
787
+ return;
788
+ }
767
789
  await this.server._getDatabase(db);
768
790
  this.currentDb = db;
769
791
  } catch (e) {
@@ -845,7 +867,7 @@ class MysqlConnection {
845
867
  } catch (e) { /* 无法解析的 SQL 仍可 prepare */ }
846
868
  const numColumns = colDefs.length;
847
869
  const stmtId = ++this._stmtSeq;
848
- this._stmts.set(stmtId, { sql, numParams, numColumns, columnDefs: colDefs });
870
+ this._stmts.set(stmtId, { sql, numParams, numColumns, columnDefs: colDefs, types: null, longData: new Map() });
849
871
 
850
872
  const pkt = Buffer.alloc(12);
851
873
  let off = 0;
@@ -876,6 +898,33 @@ class MysqlConnection {
876
898
  }
877
899
  }
878
900
 
901
+ // #389:COM_STMT_SEND_LONG_DATA 分片按序累积到语句参数缓冲,待下一次 EXECUTE 消费
902
+ _handleStmtSendLongData(body) {
903
+ if (body.length < 6) return;
904
+ const stmtId = body.readUInt32LE(0);
905
+ const paramNo = body.readUInt16LE(4);
906
+ const stmt = this._stmts.get(stmtId);
907
+ if (!stmt) return;
908
+ const chunk = body.slice(6);
909
+ const acc = stmt.longData.get(paramNo);
910
+ if (acc) acc.push(chunk);
911
+ else stmt.longData.set(paramNo, [chunk]);
912
+ // 协议规定该命令无响应包
913
+ }
914
+
915
+ // #391:COM_STMT_RESET 清空参数绑定类型与累积的长数据,下一次 EXECUTE 必须重绑
916
+ _handleStmtReset(body) {
917
+ if (body.length >= 4) {
918
+ const stmtId = body.readUInt32LE(0);
919
+ const stmt = this._stmts.get(stmtId);
920
+ if (stmt) {
921
+ stmt.types = null;
922
+ stmt.longData.clear();
923
+ }
924
+ }
925
+ this._send(okPacket());
926
+ }
927
+
879
928
  _handleStmtExecute(body) {
880
929
  try {
881
930
  if (body.length < 9) throw new Error('malformed COM_STMT_EXECUTE');
@@ -911,11 +960,22 @@ class MysqlConnection {
911
960
  for (let i = 0; i < numParams; i++) {
912
961
  const isNull = nullBitmap[Math.floor(i / 8)] & (1 << (i % 8));
913
962
  if (isNull) { values.push(null); continue; }
914
- const type = types[i] & 0xff;
915
- const parsed = this._readParamValue(body, off, type);
963
+ const typeWord = types[i];
964
+ const type = typeWord & 0xff;
965
+ const unsigned = ((typeWord >> 8) & PARAM_UNSIGNED_FLAG) !== 0;
966
+ const parsed = this._readParamValue(body, off, type, unsigned);
916
967
  values.push(parsed.value);
917
968
  off = parsed.off;
918
969
  }
970
+ // #389:累积的 SEND_LONG_DATA 分片优先于 EXECUTE 块内同参数值,消费后清空
971
+ if (stmt.longData.size > 0) {
972
+ for (const [paramNo, chunks] of stmt.longData) {
973
+ if (paramNo >= 0 && paramNo < values.length) {
974
+ values[paramNo] = Buffer.concat(chunks).toString('utf8');
975
+ }
976
+ }
977
+ stmt.longData.clear();
978
+ }
919
979
  }
920
980
  // #211:COM_STMT_EXECUTE 的结果集恒为二进制格式,即使没有占位符
921
981
  this._handleQuery(stmt.sql, values !== null && values.length > 0 ? values : undefined, true);
@@ -924,13 +984,25 @@ class MysqlConnection {
924
984
  }
925
985
  }
926
986
 
927
- _readParamValue(buf, off, type) {
987
+ _readParamValue(buf, off, type, unsigned = false) {
928
988
  switch (type) {
929
989
  case MYSQL_TYPE_NULL: return { value: null, off };
930
- case 0x01: { const v = buf.readInt8(off); return { value: v, off: off + 1 }; } // TINY
931
- case 0x02: { const v = buf.readInt16LE(off); return { value: v, off: off + 2 }; } // SHORT
932
- case 0x03: { const v = buf.readInt32LE(off); return { value: v, off: off + 4 }; } // LONG
933
- case 0x08: { const v = buf.readBigInt64LE(off); return { value: Number(v), off: off + 8 }; } // LONGLONG
990
+ case 0x01: { // TINY
991
+ const v = unsigned ? buf.readUInt8(off) : buf.readInt8(off);
992
+ return { value: v, off: off + 1 };
993
+ }
994
+ case 0x02: { // SHORT
995
+ const v = unsigned ? buf.readUInt16LE(off) : buf.readInt16LE(off);
996
+ return { value: v, off: off + 2 };
997
+ }
998
+ case 0x03: { // LONG
999
+ const v = unsigned ? buf.readUInt32LE(off) : buf.readInt32LE(off);
1000
+ return { value: v, off: off + 4 };
1001
+ }
1002
+ case 0x08: { // LONGLONG
1003
+ const v = unsigned ? buf.readBigUInt64LE(off) : buf.readBigInt64LE(off);
1004
+ return { value: Number(v), off: off + 8 };
1005
+ }
934
1006
  case 0x04: { const v = buf.readFloatLE(off); return { value: v, off: off + 4 }; } // FLOAT
935
1007
  case MYSQL_TYPE_DOUBLE: { const v = buf.readDoubleLE(off); return { value: v, off: off + 8 }; }
936
1008
  case 0x0a: case 0x07: case 0x0b: case MYSQL_TYPE_DATETIME: { // DATE/TIMESTAMP/DATETIME/TIME
@@ -978,6 +1050,18 @@ class MysqlConnection {
978
1050
  _handleQuery(sql, values, binary = false) {
979
1051
  (async () => {
980
1052
  try {
1053
+ // #393:SET NAMES <charset> [COLLATE ...] 同时切换 client/connection/results 字符集
1054
+ const namesMatch = sql.match(/^\s*SET\s+NAMES\s+([A-Za-z0-9_]+)(?:\s+COLLATE\s+[A-Za-z0-9_]+)?\s*;?\s*$/i);
1055
+ if (namesMatch) {
1056
+ const cs = namesMatch[1].toLowerCase();
1057
+ this.session.sysvars['character_set_client'] = cs;
1058
+ this.session.sysvars['character_set_connection'] = cs;
1059
+ this.session.sysvars['character_set_results'] = cs;
1060
+ this.session.charset = cs;
1061
+ this.session.charsetNr = charsetNrByName(cs);
1062
+ this._send(okPacket());
1063
+ return;
1064
+ }
981
1065
  const hasParams = values !== undefined && values !== null && values.length > 0;
982
1066
  const processedSql = hasParams ? applyParams(sql, values) : sql;
983
1067
  const statements = splitStatements(processedSql);
@@ -987,7 +1071,9 @@ class MysqlConnection {
987
1071
  for (let si = 0; si < statements.length; si++) {
988
1072
  const stmtSql = statements[si];
989
1073
  // #210:非末结果必须置 SERVER_MORE_RESULTS_EXISTS,客户端才会继续读下一个结果集
990
- const status = SERVER_STATUS_AUTOCOMMIT | (si < statements.length - 1 ? SERVER_MORE_RESULTS_EXISTS : 0);
1074
+ const status = SERVER_STATUS_AUTOCOMMIT
1075
+ | (this._inTransaction ? SERVER_STATUS_IN_TRANS : 0)
1076
+ | (si < statements.length - 1 ? SERVER_MORE_RESULTS_EXISTS : 0);
991
1077
  const stmt = parseSQL(stmtSql);
992
1078
  switch (stmt.type) {
993
1079
  case 'use': {
@@ -1049,6 +1135,15 @@ class MysqlConnection {
1049
1135
  if (r.type === 'select' || r.type === 'showTables' || r.type === 'showDatabases' || r.type === 'describe'
1050
1136
  || r.type === 'showColumns' || r.type === 'showIndex' || r.type === 'showCreateTable'
1051
1137
  || r.type === 'showVariables' || r.type === 'showStatus' || r.type === 'showGrants' || r.type === 'showWarnings') {
1138
+ if (r.type === 'showVariables') {
1139
+ // #393:会话 sysvars(如 SET NAMES 写入的 character_set_connection)覆盖内置默认值
1140
+ for (const row of r.rows || []) {
1141
+ if (Array.isArray(row)) {
1142
+ const key = String(row[0]).toLowerCase();
1143
+ if (this.session.sysvars[key] !== undefined) row[1] = String(this.session.sysvars[key]);
1144
+ }
1145
+ }
1146
+ }
1052
1147
  this.session.foundRows = (r.raw && r.raw.length !== undefined) ? r.raw.length : (r.rows ? r.rows.length : 0);
1053
1148
  let schema = null;
1054
1149
  if (r.table) {
@@ -1057,18 +1152,24 @@ class MysqlConnection {
1057
1152
  : (engine._schemas ? engine._schemas[r.table] : null);
1058
1153
  }
1059
1154
  const { packets, sequence } = binary
1060
- ? binaryResultSetPacket(r, schema, this.sequence, status)
1061
- : resultSetPacket(r, schema, this.sequence, null, status);
1155
+ ? binaryResultSetPacket(r, schema, this.sequence, status, this.session.charsetNr)
1156
+ : resultSetPacket(r, schema, this.sequence, null, status, this.session.charsetNr);
1062
1157
  this.sequence = sequence;
1063
1158
  this.socket.write(Buffer.concat(packets));
1064
1159
  } else {
1160
+ // #372:BEGIN 之后置位,COMMIT/ROLLBACK 之后清零;OK 包按执行后的状态回
1161
+ if (r.type === 'begin') this._inTransaction = true;
1162
+ else if (r.type === 'commit' || r.type === 'rollback') this._inTransaction = false;
1065
1163
  if (r.type === 'insert') {
1066
1164
  this.session.lastInsertId = r.insertId;
1067
1165
  this.session.rowCount = r.affectedRows;
1068
1166
  } else if (r.type === 'update' || r.type === 'delete' || r.type === 'truncate') {
1069
1167
  this.session.rowCount = r.affectedRows;
1070
1168
  }
1071
- this._send(okPacket(r.affectedRows || 0, r.insertId || 0, status));
1169
+ const afterStatus = SERVER_STATUS_AUTOCOMMIT
1170
+ | (this._inTransaction ? SERVER_STATUS_IN_TRANS : 0)
1171
+ | (si < statements.length - 1 ? SERVER_MORE_RESULTS_EXISTS : 0);
1172
+ this._send(okPacket(r.affectedRows || 0, r.insertId || 0, afterStatus));
1072
1173
  }
1073
1174
  }
1074
1175
  } catch (e) {
@@ -235,8 +235,25 @@ function applyModifier(doc, update, opts = {}) {
235
235
  }
236
236
  } else if (op === '$rename') {
237
237
  for (const [from, to] of Object.entries(payload)) {
238
+ // #413:源路径与目标路径互为前缀(如 a → a.b)属于自引用冲突,
239
+ // 真实 MongoDB 不允许在同一子树内移动字段;先检测并报错,
240
+ // 不能先写嵌套目标再删源把整棵源子树(含刚写入的目标)一起抹掉。
241
+ const fromParts = String(from).split('.');
242
+ const toParts = String(to).split('.');
243
+ const common = Math.min(fromParts.length, toParts.length);
244
+ let prefix = true;
245
+ for (let i = 0; i < common; i++) {
246
+ if (fromParts[i] !== toParts[i]) { prefix = false; break; }
247
+ }
248
+ if (prefix && fromParts.length !== toParts.length) {
249
+ throw new Error(`$rename: source path '${from}' and target path '${to}' overlap; cannot rename within the same subtree`);
250
+ }
238
251
  const v = getPath(doc, from);
239
- if (v !== undefined) { setPath(doc, to, v); unsetPath(doc, from); }
252
+ if (v !== undefined) {
253
+ // 先写目标、再删源叶子路径;unsetPath 只移除源叶子,不连带删除目标嵌套与兄弟字段。
254
+ setPath(doc, to, v);
255
+ unsetPath(doc, from);
256
+ }
240
257
  }
241
258
  } else if (op === '$currentDate') {
242
259
  const now = new Date().toISOString();
package/lib/objectid.js CHANGED
@@ -12,6 +12,8 @@
12
12
  * 排序比较(< >)走 Symbol.toPrimitive → hex 字符串,字典序即字节序。
13
13
  */
14
14
 
15
+ const crypto = require('crypto');
16
+
15
17
  const HEX_RE = /^[0-9a-f]{24}$/;
16
18
 
17
19
  class ObjectId {
@@ -60,6 +62,19 @@ class ObjectId {
60
62
  static fromHex(hex) {
61
63
  return new ObjectId(hex);
62
64
  }
65
+
66
+ /**
67
+ * 生成新 ObjectId(#430:insert 缺省 `_id` 时服务端兜底)。
68
+ * 布局遵循 BSON ObjectId 规范:4 字节大端秒级时间戳 + 5 字节随机 + 3 字节递增计数器。
69
+ */
70
+ static generate() {
71
+ const bytes = Buffer.alloc(12);
72
+ bytes.writeUInt32BE(Math.floor(Date.now() / 1000), 0);
73
+ crypto.randomBytes(5).copy(bytes, 4);
74
+ ObjectId._counter = ((ObjectId._counter ?? Math.floor(Math.random() * 0xffffff)) + 1) & 0xffffff;
75
+ bytes.writeUIntBE(ObjectId._counter, 9, 3);
76
+ return new ObjectId(bytes);
77
+ }
63
78
  }
64
79
 
65
80
  /**
package/lib/pg_server.js CHANGED
@@ -43,26 +43,57 @@ function pgSchemaType(def) {
43
43
  if (!def) return 'string';
44
44
  if (def.intType === 'bigint') return 'bigint';
45
45
  if (def.numericType === 'numeric') return 'numeric';
46
+ if (def.rawType) return def.rawType;
46
47
  return def.type;
47
48
  }
48
49
 
49
- function pgTypeOid(sqlType, def) {
50
+ // 类型 OID 口径:PostgreSQL 16 pg_type.h(#371)
51
+ function pgTypeOid(sqlType) {
50
52
  const t = String(sqlType || '').toLowerCase();
51
- if (t === 'bigint') return 20; // int8
52
- if (t === 'numeric' || t === 'decimal') return 1700;
53
- if (t === 'integer') return 23;
54
- if (t === 'number') return 701;
55
- if (t === 'boolean') return 16;
56
- if (t === 'date') return 1082;
57
- if (t === 'datetime' || t === 'timestamp') return 1114;
58
- if (t === 'object') return 3802;
59
- if (t === 'array') return 114;
60
- return 1043;
53
+ switch (t) {
54
+ case 'bigint': case 'int8': case 'bigserial': return 20;
55
+ case 'smallint': case 'int2': return 21;
56
+ case 'integer': case 'int': case 'int4': case 'serial': return 23;
57
+ case 'boolean': case 'bool': return 16;
58
+ case 'bytea': return 17;
59
+ case 'text': case 'string': case 'name': return 25;
60
+ case 'char': return 18;
61
+ case 'varchar': case 'bpchar': case 'character varying': return 1043;
62
+ case 'date': return 1082;
63
+ case 'time': return 1083;
64
+ case 'timestamp': case 'datetime': return 1114;
65
+ case 'timestamptz': return 1184;
66
+ case 'real': case 'float4': return 700;
67
+ case 'double': case 'double precision': case 'float': case 'float8': case 'number': return 701;
68
+ case 'numeric': case 'decimal': return 1700;
69
+ case 'json': return 114;
70
+ case 'jsonb': case 'object': return 3802;
71
+ case 'uuid': return 2950;
72
+ case 'array': return 1009; // text[] 兜底(引擎未保留元素类型)
73
+ default: return 1043;
74
+ }
75
+ }
76
+
77
+ // RowDescription.typlen:定长类型给字节宽,变长类型给 -1(#371)
78
+ function pgTypeLen(sqlType) {
79
+ const t = String(sqlType || '').toLowerCase();
80
+ if (t === 'boolean' || t === 'bool') return 1;
81
+ if (t === 'smallint' || t === 'int2') return 2;
82
+ if (t === 'integer' || t === 'int' || t === 'int4' || t === 'serial') return 4;
83
+ if (t === 'bigint' || t === 'int8' || t === 'bigserial') return 8;
84
+ if (t === 'real' || t === 'float4') return 4;
85
+ if (t === 'double' || t === 'double precision' || t === 'float' || t === 'float8' || t === 'number') return 8;
86
+ return -1;
61
87
  }
62
88
 
63
89
  function pgFormatValue(value, sqlType) {
64
90
  if (value === null || value === undefined) return null;
65
91
  const t = String(sqlType || '').toLowerCase();
92
+ // #386:bytea 文本输出按 PG 默认 bytea_output=hex:`\x` + 小写十六进制
93
+ if (t === 'bytea') {
94
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(String(value), 'utf8');
95
+ return '\\x' + buf.toString('hex');
96
+ }
66
97
  if (t === 'boolean') return value === true || value === 1 || value === 'true' || value === 't' ? 't' : 'f';
67
98
  if (t === 'object') {
68
99
  if (typeof value === 'string') return value;
@@ -179,7 +210,7 @@ function buildRowDescription(columns, types, formats) {
179
210
  p.i32(0); // table oid
180
211
  p.i16(0); // column attnum
181
212
  p.i32(pgTypeOid(types[i]));
182
- p.i16(types[i] === 'integer' ? 4 : (types[i] === 'bigint' ? 8 : (types[i] === 'boolean' ? 1 : -1))); // typlen
213
+ p.i16(pgTypeLen(types[i])); // typlen
183
214
  p.i32(-1); // typmod
184
215
  p.i16(fmt === 1 ? 1 : 0); // format code
185
216
  }
@@ -196,12 +227,18 @@ function buildEmptyQuery() {
196
227
  return frame(0x49, Buffer.alloc(0)); // 'I'
197
228
  }
198
229
 
199
- function buildErrorResponse(code, message, severity = 'ERROR') {
230
+ function buildErrorResponse(code, message, severity = 'ERROR', extra = {}) {
200
231
  const p = new PgBuffer();
201
232
  p.c(0x53); p.str(severity).nul(); // S
202
233
  p.c(0x56); p.str(severity).nul(); // V
203
234
  p.c(0x43); p.str(code).nul(); // C
204
235
  p.c(0x4d); p.str(message).nul(); // M
236
+ // #377:PG 客户端依赖 D/H/P 定位问题;此前这些字段完全不会出现
237
+ if (extra.detail) { p.c(0x44); p.str(extra.detail).nul(); } // D
238
+ if (extra.hint) { p.c(0x48); p.str(extra.hint).nul(); } // H
239
+ if (extra.position != null && Number.isFinite(Number(extra.position))) {
240
+ p.c(0x50); p.str(String(extra.position)).nul(); // P
241
+ }
205
242
  p.c(0x00);
206
243
  return frame(0x45, p.build()); // 'E'
207
244
  }
@@ -318,9 +355,22 @@ class PgConnection {
318
355
  this.socket = socket;
319
356
  this.server = server;
320
357
  this.buffer = Buffer.alloc(0);
358
+ this._extendedBatch = false; // #381
321
359
  this.authenticated = false;
322
360
  this.user = null;
323
361
  this.database = null;
362
+ // #375/#376:会话 GUC 表,启动包回填、SET 更新并广播 ParameterStatus
363
+ this._guc = {
364
+ application_name: '',
365
+ search_path: 'public',
366
+ client_encoding: 'UTF8',
367
+ server_encoding: 'UTF8',
368
+ DateStyle: 'ISO, MDY',
369
+ integer_datetimes: 'on',
370
+ standard_conforming_strings: 'on',
371
+ timezone: 'UTC',
372
+ bytea_output: 'hex'
373
+ };
324
374
  this._scram = null;
325
375
  this._scramClientFirst = null;
326
376
  this._scramServerFirst = null;
@@ -403,8 +453,15 @@ class PgConnection {
403
453
  await this._handleMessage(type, body);
404
454
  }
405
455
  } catch (e) {
406
- this._send(buildErrorResponse((e && e.sqlState) || 'XX000', e && e.message ? e.message : String(e)));
407
- this._send(buildReadyForQuery(this._rfqStatus()));
456
+ this._send(buildErrorResponse(
457
+ (e && e.sqlState) || 'XX000',
458
+ e && e.message ? e.message : String(e),
459
+ 'ERROR',
460
+ { position: (e && e.position) ||
461
+ (() => { const m = /at position (\d+)/.exec(String((e && e.message) || '')); return m ? Number(m[1]) : undefined; })(),
462
+ detail: e && e.detail, hint: e && e.hint }));
463
+ // #381:扩展协议错误不能在 Sync 之前发 ReadyForQuery,否则 Sync 再发一帧 → 双 Z
464
+ if (!this._extendedBatch) this._send(buildReadyForQuery(this._rfqStatus()));
408
465
  }
409
466
  });
410
467
  }
@@ -448,6 +505,10 @@ class PgConnection {
448
505
  }
449
506
  this.user = params.user || 'postgres';
450
507
  this.database = params.database || this.user;
508
+ // #376:保留启动包携带的会话参数,认证后随 ParameterStatus 回填
509
+ for (const k of ['application_name', 'search_path', 'client_encoding', 'DateStyle', 'timezone', 'standard_conforming_strings']) {
510
+ if (params[k] !== undefined) this._guc[k] = params[k];
511
+ }
451
512
  this._pid = 10000 + (this.server._connSeq++ % 8000);
452
513
  this._secret = Math.floor(Math.random() * 0x7fffffff);
453
514
  this._startAuth();
@@ -528,11 +589,14 @@ class PgConnection {
528
589
  this.authenticated = true;
529
590
  this._send(frame(0x52, (() => { const p = new PgBuffer(); p.i32(AUTH_OK); return p.build(); })()));
530
591
  this._send(buildParameterStatus('server_version', '16.4 (jsql-neo ' + this.server.version + ')'));
531
- this._send(buildParameterStatus('server_encoding', 'UTF8'));
532
- this._send(buildParameterStatus('client_encoding', 'UTF8'));
533
- this._send(buildParameterStatus('DateStyle', 'ISO, MDY'));
534
- this._send(buildParameterStatus('integer_datetimes', 'on'));
535
- this._send(buildParameterStatus('standard_conforming_strings', 'on'));
592
+ this._send(buildParameterStatus('server_encoding', this._guc.server_encoding));
593
+ this._send(buildParameterStatus('client_encoding', this._guc.client_encoding));
594
+ this._send(buildParameterStatus('DateStyle', this._guc.DateStyle));
595
+ this._send(buildParameterStatus('integer_datetimes', this._guc.integer_datetimes));
596
+ this._send(buildParameterStatus('standard_conforming_strings', this._guc.standard_conforming_strings));
597
+ // #376:启动包提交的会话参数(含空 application_name)认证后回填
598
+ this._send(buildParameterStatus('application_name', this._guc.application_name || ''));
599
+ this._send(buildParameterStatus('search_path', this._guc.search_path || 'public'));
536
600
  this._send(buildBackendKeyData(this._pid, this._secret));
537
601
  this._send(buildReadyForQuery('I'));
538
602
  }
@@ -544,6 +608,7 @@ class PgConnection {
544
608
  async _handleMessage(type, body) {
545
609
  switch (type) {
546
610
  case 0x50: { // 'P' parse
611
+ this._extendedBatch = true;
547
612
  const parts = this._splitCStrings(body);
548
613
  const name = parts[0], sql = parts[1];
549
614
  const nParams = body.readInt16BE(this._cstringLen(body, 0) + this._cstringLen(body, this._cstringLen(body, 0)));
@@ -555,6 +620,7 @@ class PgConnection {
555
620
  break;
556
621
  }
557
622
  case 0x42: { // 'B' bind
623
+ this._extendedBatch = true;
558
624
  const n0 = this._cstringLen(body, 0);
559
625
  const portal = body.toString('utf8', 0, n0 - 1);
560
626
  const stmtName = body.toString('utf8', n0, n0 + this._cstringLen(body, n0) - 1);
@@ -599,18 +665,22 @@ class PgConnection {
599
665
  this._send(buildBindComplete()); break;
600
666
  }
601
667
  case 0x44: // 'D' describe
668
+ this._extendedBatch = true;
602
669
  this._handleDescribe(body);
603
670
  break;
604
671
  case 0x45: { // 'E' execute
672
+ this._extendedBatch = true;
605
673
  const portalName = body.toString('utf8', 0, this._cstringLen(body, 0) - 1);
606
674
  const portal = this._portal.get(portalName);
607
675
  if (!portal) throw new Error(`portal "${portalName}" does not exist`);
608
676
  return this._execute(portal);
609
677
  }
610
678
  case 0x43: // 'C' close
679
+ this._extendedBatch = true;
611
680
  this._handleClose(body);
612
681
  break;
613
682
  case 0x53: // 'S' sync
683
+ this._extendedBatch = false;
614
684
  this._send(buildReadyForQuery(this._rfqStatus()));
615
685
  break;
616
686
  case 0x46: // 'F' function call
@@ -656,7 +726,9 @@ class PgConnection {
656
726
  // #309:无参语句 ParameterDescription 应为 paramCount=0
657
727
  this._send(buildParameterDesc(stmt.paramTypes || []));
658
728
  const cols = this._describeCols(stmt.sql);
659
- if (cols && cols.length > 0) {
729
+ // #352:_describeCols 返回 { columns, types } 对象,此前误判 cols.length 恒为 undefined,
730
+ // 导致 SELECT 的 Describe statement 一律回 NoData,从不发 RowDescription。
731
+ if (cols && cols.columns && cols.columns.length > 0) {
660
732
  this._send(buildRowDescription(cols.columns, cols.types));
661
733
  } else {
662
734
  this._send(buildNoData());
@@ -730,7 +802,13 @@ class PgConnection {
730
802
 
731
803
  async _handleSimpleQuery(sql) {
732
804
  const trimmed = sql.trim();
733
- if (!trimmed) {
805
+ // #387:只含空白/分号/注释的查询串不包含任何 SQL 语句,按协议必须回 EmptyQueryResponse。
806
+ const effective = trimmed
807
+ .replace(/\/\*[\s\S]*?\*\//g, '')
808
+ .replace(/--[^\r\n]*/g, '')
809
+ .replace(/;/g, '')
810
+ .trim();
811
+ if (!effective) {
734
812
  this._send(buildEmptyQuery());
735
813
  this._send(buildReadyForQuery(this._rfqStatus()));
736
814
  return;
@@ -741,22 +819,70 @@ class PgConnection {
741
819
  this._send(buildReadyForQuery(this._rfqStatus()));
742
820
  return;
743
821
  }
744
- if (trimmed.startsWith('SET ')) {
745
- this._send(buildCommandComplete('SET'));
746
- this._send(buildReadyForQuery(this._rfqStatus()));
822
+ if (/^SET\b/i.test(trimmed)) {
823
+ this._handleSet(trimmed);
747
824
  return;
748
825
  }
749
826
  try {
750
827
  await this._executeSql(sql, null, null);
751
828
  } catch (e) {
752
829
  if (this._inTransaction) this._txAborted = true;
753
- this._send(buildErrorResponse(this._pgErrorCode(e), e && e.message ? e.message : String(e)));
830
+ this._send(buildErrorResponse(
831
+ this._pgErrorCode(e),
832
+ e && e.message ? e.message : String(e),
833
+ 'ERROR',
834
+ { position: (e && e.position) ||
835
+ (() => { const m = /at position (\d+)/.exec(String((e && e.message) || '')); return m ? Number(m[1]) : undefined; })(),
836
+ detail: e && e.detail, hint: e && e.hint }));
754
837
  this._send(buildReadyForQuery(this._rfqStatus()));
755
838
  return;
756
839
  }
757
840
  this._send(buildReadyForQuery(this._rfqStatus()));
758
841
  }
759
842
 
843
+ // #375:SET 解析会话 GUC,更新会话表并广播 ParameterStatus;未识别参数回 42704。
844
+ _handleSet(sql) {
845
+ const m = /^SET\s+(?:SESSION\s+|LOCAL\s+)?([A-Za-z_][A-Za-z0-9_.]*)\s*(?:TO|=)\s*(.+?)\s*;?$/i.exec(sql);
846
+ if (!m) {
847
+ this._send(buildErrorResponse('42601', 'syntax error in SET command'));
848
+ this._send(buildReadyForQuery(this._rfqStatus()));
849
+ return;
850
+ }
851
+ const name = m[1].toLowerCase();
852
+ const rawValue = m[2].trim();
853
+ let value;
854
+ if (/^DEFAULT$/i.test(rawValue)) {
855
+ value = this._defaultGuc(name);
856
+ } else {
857
+ const q = rawValue[0];
858
+ if ((q === "'" || q === '"') && rawValue.length >= 2 && rawValue.endsWith(q)) {
859
+ value = rawValue.slice(1, -1).replace(/''/g, "'");
860
+ } else {
861
+ value = rawValue;
862
+ }
863
+ }
864
+ const known = ['application_name', 'search_path', 'client_encoding', 'server_encoding', 'DateStyle',
865
+ 'timezone', 'bytea_output', 'standard_conforming_strings', 'default_transaction_read_only', 'integer_datetimes'];
866
+ if (!known.includes(name)) {
867
+ this._send(buildErrorResponse('42704', `unrecognized configuration parameter "${m[1]}"`));
868
+ this._send(buildReadyForQuery(this._rfqStatus()));
869
+ return;
870
+ }
871
+ this._guc[name] = value;
872
+ this._send(buildParameterStatus(name, value));
873
+ this._send(buildCommandComplete('SET'));
874
+ this._send(buildReadyForQuery(this._rfqStatus()));
875
+ }
876
+
877
+ _defaultGuc(name) {
878
+ const defaults = {
879
+ application_name: '', search_path: 'public', client_encoding: 'UTF8', server_encoding: 'UTF8',
880
+ DateStyle: 'ISO, MDY', timezone: 'UTC', bytea_output: 'hex', standard_conforming_strings: 'on',
881
+ default_transaction_read_only: 'off', integer_datetimes: 'on'
882
+ };
883
+ return Object.prototype.hasOwnProperty.call(defaults, name) ? defaults[name] : '';
884
+ }
885
+
760
886
  async _execute(portal) {
761
887
  if (this._txAborted) {
762
888
  this._send(buildErrorResponse('25P02', 'current transaction is aborted, commands ignored until end of transaction block'));