From 6527fc1eb38e1d84ab5f3d3e7edc6d6deb79eb51 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Sat, 17 Oct 2026 06:53:40 +0300 Subject: [PATCH 1/2] perf(grid): sort timestamp columns without a local DateTime per row (#1533) Sorting by a date / timestamp column parsed each cell with DateTime.tryParse. Nearly all of its cost is the local constructor it ends in, which asks the system for the zone offset on every call (and re-reads the zone file when TZ is not set): 50,000 timestamps took ~400 ms. isoMicrosSinceEpoch reads the shapes drivers print (YYYY-MM-DD, then optional [T ]HH:MM, :SS, .fraction, Z / +-HH[[:]MM]) from the code units and returns the same instant: zoned values through DateTime.utc, local ones through DateTime.utc plus the day's offset, looked up once per day per sort; a day whose offset changes (DST) still uses the local constructor. Other shapes go to DateTime.tryParse as before. Keys are ints instead of DateTime objects. Standalone Dart AOT, 50,000 timestamps, TZ unset: ~400 ms -> ~60 ms. Same instants as DateTime.tryParse on 200,000 values in four zones (Moscow, Berlin, New York, Lord Howe); same order on mixed columns. --- lib/features/workspace/grid/grid_sorting.dart | 140 +++++++++++++++++- .../workspace/grid_sort_dates_test.dart | 70 +++++++++ 2 files changed, 202 insertions(+), 8 deletions(-) create mode 100644 test/features/workspace/grid_sort_dates_test.dart diff --git a/lib/features/workspace/grid/grid_sorting.dart b/lib/features/workspace/grid/grid_sorting.dart index e2ea3ea8..7ec46022 100644 --- a/lib/features/workspace/grid/grid_sorting.dart +++ b/lib/features/workspace/grid/grid_sorting.dart @@ -13,19 +13,21 @@ enum _SortKeyType { nullOrEmpty, numeric, dateTime, string } class _SortKey implements Comparable<_SortKey> { final _SortKeyType type; final num? numVal; - final DateTime? dtVal; + + /// The instant of a date / timestamp, in microseconds since the epoch. + final int dtMicros; final String strLower; final String strRaw; _SortKey._({ required this.type, this.numVal, - this.dtVal, + this.dtMicros = 0, this.strLower = '', this.strRaw = '', }); - factory _SortKey.parse(String val) { + factory _SortKey.parse(String val, Map localOffsets) { if (val == 'NULL' || val.isEmpty) { return _SortKey._(type: _SortKeyType.nullOrEmpty); } @@ -33,9 +35,14 @@ class _SortKey implements Comparable<_SortKey> { if (n != null) { return _SortKey._(type: _SortKeyType.numeric, numVal: n, strRaw: val); } - final dt = DateTime.tryParse(val); - if (dt != null) { - return _SortKey._(type: _SortKeyType.dateTime, dtVal: dt, strRaw: val); + final micros = isoMicrosSinceEpoch(val, localOffsets: localOffsets) ?? + DateTime.tryParse(val)?.microsecondsSinceEpoch; + if (micros != null) { + return _SortKey._( + type: _SortKeyType.dateTime, + dtMicros: micros, + strRaw: val, + ); } return _SortKey._( type: _SortKeyType.string, @@ -57,7 +64,7 @@ class _SortKey implements Comparable<_SortKey> { return numVal!.compareTo(other.numVal!); } if (type == _SortKeyType.dateTime && other.type == _SortKeyType.dateTime) { - return dtVal!.compareTo(other.dtVal!); + return dtMicros.compareTo(other.dtMicros); } final aLower = @@ -72,6 +79,122 @@ class _SortKey implements Comparable<_SortKey> { } } +/// [s] as `DateTime.parse(s).microsecondsSinceEpoch` for the shapes database +/// drivers print, read from the code units: `YYYY-MM-DD`, then optionally +/// `[T ]HH:MM`, `:SS`, `.fraction` and `Z` / `±HH[[:]MM]`. Null for any other +/// shape, which the caller hands to [DateTime.tryParse]: this is only a +/// shortcut past its regex, with the same result (#1533). +/// +/// Without a zone the time is local, as in [DateTime.parse]; fields out of +/// range roll over the same way, because they go through the same +/// constructors. The fraction keeps its first six digits, as there. +/// +/// The local constructor asks the system for the zone offset on every call +/// (~4 µs, nearly all of a timestamp sort). With [localOffsets], one map per +/// sort, a day whose offset is the same at its start and its end is looked +/// up once and the time is computed from the UTC fields; a day with a +/// daylight-saving change still goes through the local constructor. +@foundation.visibleForTesting +int? isoMicrosSinceEpoch(String s, {Map? localOffsets}) { + final n = s.length; + int digits(int at, int count) { + if (at + count > n) return -1; + var v = 0; + for (var i = at; i < at + count; i++) { + final c = s.codeUnitAt(i) - 0x30; + if (c < 0 || c > 9) return -1; + v = v * 10 + c; + } + return v; + } + + if (n < 10 || s.codeUnitAt(4) != 0x2D || s.codeUnitAt(7) != 0x2D) { + return null; + } + final year = digits(0, 4); + final month = digits(5, 2); + final day = digits(8, 2); + if (year < 0 || month < 0 || day < 0) return null; + var hour = 0, minute = 0, second = 0, milli = 0, micro = 0; + var i = 10; + if (i < n) { + final sep = s.codeUnitAt(i); + if (sep != 0x54 && sep != 0x74 && sep != 0x20) return null; // T t ' ' + hour = digits(i + 1, 2); + if (hour < 0 || i + 3 >= n || s.codeUnitAt(i + 3) != 0x3A) return null; + minute = digits(i + 4, 2); + if (minute < 0) return null; + i += 6; + if (i < n && s.codeUnitAt(i) == 0x3A) { + second = digits(i + 1, 2); + if (second < 0) return null; + i += 3; + if (i < n && s.codeUnitAt(i) == 0x2E) { + i++; + final start = i; + var fraction = 0; + while (i < n) { + final c = s.codeUnitAt(i) - 0x30; + if (c < 0 || c > 9) break; + if (i - start < 6) fraction = fraction * 10 + c; + i++; + } + if (i == start) return null; + for (var k = i - start; k < 6; k++) { + fraction *= 10; + } + milli = fraction ~/ 1000; + micro = fraction % 1000; + } + } + } + if (i == n) { + if (localOffsets != null) { + final wall = DateTime.utc( + year, month, day, hour, minute, second, milli, micro); + final key = wall.year * 10000 + wall.month * 100 + wall.day; + final offset = localOffsets[key] ??= + _dayOffsetMicros(wall.year, wall.month, wall.day); + if (offset != _offsetChangesThatDay) { + return wall.microsecondsSinceEpoch - offset; + } + } + return DateTime(year, month, day, hour, minute, second, milli, micro) + .microsecondsSinceEpoch; + } + var offsetMinutes = 0; + final z = s.codeUnitAt(i); + if (z == 0x5A || z == 0x7A) { + if (i + 1 != n) return null; + } else if (z == 0x2B || z == 0x2D) { + final hh = digits(i + 1, 2); + if (hh < 0) return null; + i += 3; + var mm = 0; + if (i < n) { + if (s.codeUnitAt(i) == 0x3A) i++; + mm = digits(i, 2); + if (mm < 0 || i + 2 != n) return null; + } + offsetMinutes = (hh * 60 + mm) * (z == 0x2D ? -1 : 1); + } else { + return null; + } + return DateTime.utc(year, month, day, hour, minute, second, milli, micro) + .microsecondsSinceEpoch - + offsetMinutes * Duration.microsecondsPerMinute; +} + +const int _offsetChangesThatDay = 1 << 62; + +/// The local zone's offset (µs) on that day, or [_offsetChangesThatDay] when +/// it is not the same at the first and the last second of the day. +int _dayOffsetMicros(int year, int month, int day) { + final start = DateTime(year, month, day).timeZoneOffset; + final end = DateTime(year, month, day, 23, 59, 59).timeZoneOffset; + return start == end ? start.inMicroseconds : _offsetChangesThatDay; +} + /// Result of sorting rows in [VirtualResultGrid], preserving model indices. class SortedResultGridData { final List> rows; @@ -99,11 +222,12 @@ SortedResultGridData sortResultGridRowsWithIndices({ ); } final n = rows.length; + final localOffsets = {}; final keys = List<_SortKey>.generate(n, (i) { final row = rows[i]; final val = columnIndex < row.length ? row[columnIndex] : ''; - return _SortKey.parse(val); + return _SortKey.parse(val, localOffsets); }, growable: false); final indices = List.generate(n, (i) => i, growable: false); diff --git a/test/features/workspace/grid_sort_dates_test.dart b/test/features/workspace/grid_sort_dates_test.dart new file mode 100644 index 00000000..11f8c733 --- /dev/null +++ b/test/features/workspace/grid_sort_dates_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:querya_desktop/features/workspace/grid/grid_sorting.dart'; + +/// #1533: date keys are read without DateTime.parse's local constructor per +/// row, with the same instants and therefore the same order. +void main() { + int? reference(String s) => DateTime.tryParse(s)?.microsecondsSinceEpoch; + int? fast(String s, Map cache) => + isoMicrosSinceEpoch(s, localOffsets: cache) ?? reference(s); + + const shapes = [ + '2026-01-02', + '2026-01-02T03:04', + '2026-01-02T03:04:05', + '2026-01-02 03:04:05.123', + '2026-01-02T03:04:05.1234567', + '2026-01-02T03:04:05Z', + '2026-01-02t03:04:05z', + '2026-01-02T03:04:05.5+03:00', + '2026-01-02T03:04:05-0530', + '2026-01-02T03:04:05+02', + '2026-02-30 12:00', + '2026-01-02T25:61:61', + // Daylight-saving changes in Europe and the US, and the hours around them. + '2026-03-29T01:59:59', '2026-03-29T02:30', '2026-03-29T03:00', + '2026-10-25T01:30', '2026-10-25T02:30', '2026-10-25T03:00', + '2026-03-08T02:30', '2026-11-01T01:30', + // Shapes left to DateTime.tryParse. + '20260102', '2026-01-02T10', '2026-01-02 Z', '+2026-01-02', 'x', '', + ]; + + test('the same instant as DateTime.parse for every shape', () { + final cache = {}; + for (final s in shapes) { + expect(fast(s, cache), reference(s), reason: s); + } + // A second pass reads the cached offsets. + for (final s in shapes) { + expect(fast(s, cache), reference(s), reason: 'cached: $s'); + } + }); + + test('shapes it does not read are left to DateTime.tryParse', () { + for (final s in ['20260102', '2026-01-02T10', '2026-01-02 Z', 'x', '']) { + expect(isoMicrosSinceEpoch(s), isNull, reason: s); + } + }); + + test('a timestamp column sorts by time, NULL and empty last', () { + final rows = [ + ['2026-01-02T10:00:00'], + ['NULL'], + ['2025-12-31 23:59:59.999'], + [''], + ['2026-01-02T09:00:00Z'], + ['2026-01-01'], + ]; + final asc = sortResultGridRowsWithIndices( + rows: rows, + columnIndex: 0, + order: ResultGridSortOrder.ascending, + ); + final instants = [ + for (final i in asc.sortedToModelIndices.take(4)) + DateTime.parse(rows[i][0]).microsecondsSinceEpoch, + ]; + expect(instants, [...instants]..sort()); + expect(asc.sortedToModelIndices.skip(4).toSet(), {1, 3}); + }); +} From fa372d57a5bcdfce84ce73afc6a7204c411def6b Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Sat, 17 Oct 2026 07:01:22 +0300 Subject: [PATCH 2/2] fix(grid): a lower-case t is not a date-time separator for DateTime.parse (#1533) isoMicrosSinceEpoch took '2026-01-02t03:04:05' as a timestamp, which DateTime.parse refuses, so such a cell sorted as a date instead of as text. Only 'T' and a space are accepted now; the parity test caught it and the fuzz check now includes the shape. --- lib/features/workspace/grid/grid_sorting.dart | 3 ++- test/features/workspace/grid_sort_dates_test.dart | 9 ++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/features/workspace/grid/grid_sorting.dart b/lib/features/workspace/grid/grid_sorting.dart index 7ec46022..d8f46235 100644 --- a/lib/features/workspace/grid/grid_sorting.dart +++ b/lib/features/workspace/grid/grid_sorting.dart @@ -119,7 +119,8 @@ int? isoMicrosSinceEpoch(String s, {Map? localOffsets}) { var i = 10; if (i < n) { final sep = s.codeUnitAt(i); - if (sep != 0x54 && sep != 0x74 && sep != 0x20) return null; // T t ' ' + // `T` or a space, as DateTime.parse takes; a lower-case `t` it does not. + if (sep != 0x54 && sep != 0x20) return null; hour = digits(i + 1, 2); if (hour < 0 || i + 3 >= n || s.codeUnitAt(i + 3) != 0x3A) return null; minute = digits(i + 4, 2); diff --git a/test/features/workspace/grid_sort_dates_test.dart b/test/features/workspace/grid_sort_dates_test.dart index 11f8c733..867e7a44 100644 --- a/test/features/workspace/grid_sort_dates_test.dart +++ b/test/features/workspace/grid_sort_dates_test.dart @@ -41,7 +41,14 @@ void main() { }); test('shapes it does not read are left to DateTime.tryParse', () { - for (final s in ['20260102', '2026-01-02T10', '2026-01-02 Z', 'x', '']) { + for (final s in [ + '20260102', + '2026-01-02T10', + '2026-01-02 Z', + '2026-01-02t03:04:05', + 'x', + '', + ]) { expect(isoMicrosSinceEpoch(s), isNull, reason: s); } });