Skip to content

Commit 71dc643

Browse files
fix(mongodb): nested ObjectId / ISODate / NumberLong in MQL become BSON values (#1667) (#1673)
The relaxed parser turns ObjectId(...) and ISODate(...) inside an argument into {"$oid": ...} / {"$date": ...}, and nothing on the query-workspace path converted them: find({_id: ObjectId(...)}) sent {_id: {$oid: ...}} and matched nothing, insertOne stored a sub-document. Every parsed argument now has single-key {$oid: <24 hex>}, {$date: <ISO | ms | {$numberLong}>} and {$numberLong: <n>} maps turned into ObjectId, UTC DateTime and int, at any depth, whether the relaxed syntax produced them or the user typed Extended JSON. Other maps, query operators such as $regex / $options included, stay as written. ISODate without a zone is UTC, as in mongosh, also for a top-level ISODate(...) argument (it was local time).
1 parent 70d98d9 commit 71dc643

2 files changed

Lines changed: 103 additions & 2 deletions

File tree

‎lib/features/mongodb/mql_parser.dart‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,61 @@ class MqlParser {
539539

540540
// ─── Relaxed JSON / JS Object Literal Parser ────────────────────────────────
541541

542-
static dynamic _parseRelaxedJson(String text) {
542+
/// [_parseValue] with the Extended JSON wrappers inside it turned into
543+
/// BSON values (#1667): the relaxed syntax writes nested `ObjectId(...)` /
544+
/// `ISODate(...)` as `{"$oid": ...}` / `{"$date": ...}`, and users type them
545+
/// in JSON; sent as maps they matched nothing or were stored as
546+
/// sub-documents.
547+
static dynamic _parseRelaxedJson(String text) =>
548+
_bsonScalars(_parseValue(text));
549+
550+
/// `{"$oid": "<24 hex>"}` -> [ObjectId], `{"$date": ...}` -> UTC
551+
/// [DateTime], `{"$numberLong": "<n>"}` -> int, at any depth of [value].
552+
/// Only single-key maps of exactly these shapes: query operators such as
553+
/// `$regex` / `$options` stay as written.
554+
static Object? _bsonScalars(Object? value) {
555+
if (value is List) return [for (final v in value) _bsonScalars(v)];
556+
if (value is! Map) return value;
557+
if (value.length == 1) {
558+
final MapEntry(:key, value: inner) = value.entries.single;
559+
switch (key) {
560+
case r'$oid' when inner is String && ObjectId.isValidHexId(inner):
561+
return ObjectId.fromHexString(inner);
562+
case r'$date':
563+
final date = _ejsonDate(inner);
564+
if (date != null) return date;
565+
case r'$numberLong' when inner is String:
566+
final n = int.tryParse(inner);
567+
if (n != null) return n;
568+
}
569+
}
570+
return <String, dynamic>{
571+
for (final e in value.entries) e.key.toString(): _bsonScalars(e.value),
572+
};
573+
}
574+
575+
/// The value of `{"$date": ...}`: an ISO string, milliseconds, or
576+
/// `{"$numberLong": "<ms>"}` (canonical Extended JSON).
577+
static DateTime? _ejsonDate(Object? v) {
578+
if (v is String) return _isoDateUtc(v);
579+
if (v is int) return DateTime.fromMillisecondsSinceEpoch(v, isUtc: true);
580+
if (v is Map && v.length == 1 && v[r'$numberLong'] is String) {
581+
final ms = int.tryParse(v[r'$numberLong'] as String);
582+
if (ms != null) return DateTime.fromMillisecondsSinceEpoch(ms, isUtc: true);
583+
}
584+
return null;
585+
}
586+
587+
/// `ISODate(...)` as mongosh reads it: a time without a zone is UTC, not
588+
/// the local time `DateTime.parse` would make of it.
589+
static DateTime? _isoDateUtc(String s) {
590+
final d = DateTime.tryParse(s.trim());
591+
if (d == null || d.isUtc) return d;
592+
return DateTime.utc(d.year, d.month, d.day, d.hour, d.minute, d.second,
593+
d.millisecond, d.microsecond);
594+
}
595+
596+
static dynamic _parseValue(String text) {
543597
final trimmed = text.trim();
544598
if (trimmed.isEmpty) return null;
545599

@@ -554,7 +608,8 @@ class MqlParser {
554608
final iso = trimmed
555609
.substring(8, trimmed.length - 1)
556610
.replaceAll(RegExp(r'''['"]'''), '');
557-
return DateTime.parse(iso);
611+
return _isoDateUtc(iso) ??
612+
(throw FormatException('Invalid ISODate: $iso'));
558613
}
559614
if ((trimmed.startsWith('NumberLong(') || trimmed.startsWith('NumberInt(')) &&
560615
trimmed.endsWith(')')) {

‎test/features/mongodb/mql_parser_test.dart‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import 'package:flutter_test/flutter_test.dart';
2+
import 'package:mongo_dart/mongo_dart.dart' show ObjectId;
23
import 'package:querya_desktop/features/mongodb/mql_parser.dart';
34

45
void main() {
@@ -169,4 +170,49 @@ void main() {
169170
expect(sw.elapsedMilliseconds, lessThan(2000));
170171
});
171172
});
173+
174+
group('Extended JSON wrappers become BSON values (#1667)', () {
175+
const hex = '5f1d7f0b9d3e2a0017a1b2c3';
176+
177+
test('a nested ObjectId(...) in a filter is an ObjectId', () {
178+
final cmd = MqlParser.parse('db.users.find({ _id: ObjectId("$hex") })');
179+
expect(cmd.filter?['_id'], isA<ObjectId>());
180+
expect((cmd.filter?['_id'] as ObjectId).toHexString(), hex);
181+
});
182+
183+
test('ISODate(...) under an operator is a UTC DateTime', () {
184+
final cmd = MqlParser.parse(
185+
'db.events.find({ at: { \$gte: ISODate("2026-01-01") } })');
186+
final at = (cmd.filter?['at'] as Map)['\$gte'];
187+
expect(at, DateTime.utc(2026));
188+
expect((at as DateTime).isUtc, isTrue);
189+
});
190+
191+
test('insertOne stores an ObjectId, not a {\$oid} sub-document', () {
192+
final cmd =
193+
MqlParser.parse('db.users.insertOne({ owner: ObjectId(\'$hex\') })');
194+
expect(cmd.document?['owner'], isA<ObjectId>());
195+
});
196+
197+
test('Extended JSON typed in strict JSON is converted too', () {
198+
final cmd = MqlParser.parse(
199+
'db.c.find({ "_id": { "\$oid": "$hex" }, '
200+
'"at": { "\$date": { "\$numberLong": "0" } }, '
201+
'"n": { "\$numberLong": "9007199254740993" } })',
202+
);
203+
expect(cmd.filter?['_id'], isA<ObjectId>());
204+
expect(cmd.filter?['at'], DateTime.fromMillisecondsSinceEpoch(0, isUtc: true));
205+
expect(cmd.filter?['n'], 9007199254740993);
206+
});
207+
208+
test('query operators and look-alikes stay as written', () {
209+
final cmd = MqlParser.parse(
210+
'db.c.find({ name: { \$regex: "^a", \$options: "i" }, '
211+
'o: { \$oid: "not-hex" }, two: { \$date: "2026-01-01", x: 1 } })',
212+
);
213+
expect(cmd.filter?['name'], {'\$regex': '^a', '\$options': 'i'});
214+
expect(cmd.filter?['o'], {'\$oid': 'not-hex'});
215+
expect(cmd.filter?['two'], {'\$date': '2026-01-01', 'x': 1});
216+
});
217+
});
172218
}

0 commit comments

Comments
 (0)