Uploaded image for project: 'MariaDB Server'
  1. MariaDB Server
  2. MDEV-42371

LEAD() and LAG() read an offset of 2^63 or more as negative: LEAD(id, 18446744073709551614) returns the value two rows back

    XMLWordPrintable

Details

    Description

      LEAD(expr, N) returns the value of expr N rows after the current row, and NULL when that row is outside the partition. For N of 2^63 or more the offset is read as a negative number, so the function returns values from rows before the current one, with no error or warning:

      • LEAD(id, 18446744073709551614) (2^64 - 2) returns the value two rows back, the answer of LEAD(id, -2);
      • LEAD(id, 18446744073709551615) returns the value of the previous row;
      • LAG(id, 18446744073709551614) returns the value two rows ahead.

      An offset of 9223372036854775807 (2^63 - 1) returns NULL for every row, as an offset beyond the partition should.

      How to repeat

      CREATE TABLE t(id INT);
      INSERT INTO t VALUES (1),(2),(3),(4),(5);
      SELECT id, LEAD(id, 2) OVER (ORDER BY id) AS l2,
             LEAD(id, -2) OVER (ORDER BY id) AS lm2,
             LEAD(id, 9223372036854775807) OVER (ORDER BY id) AS lmax,
             LEAD(id, 18446744073709551614) OVER (ORDER BY id) AS lbig,
             LEAD(id, 18446744073709551615) OVER (ORDER BY id) AS lbig1,
             LAG(id, 18446744073709551614) OVER (ORDER BY id) AS gbig
      FROM t ORDER BY id;
      

      Output on main 392818112aa1 (13.3.0) and on 13.0.2:

      id   l2    lm2   lmax  lbig  lbig1 gbig
      1    3     NULL  NULL  NULL  NULL  3
      2    4     NULL  NULL  NULL  1     4
      3    5     1     NULL  1     2     5
      4    NULL  2     NULL  2     3     NULL
      5    NULL  3     NULL  3     4     NULL
      

      Expected

      NULL in every row of lbig, lbig1 and gbig, as in lmax, or an error. MySQL 26.10.0 rejects these offsets ("ERROR 1210 (HY000): Incorrect arguments to lead").

      Cause

      sql/sql_window.cc:2499, Frame_positional_cursor::save_offset_value():

          if (offset)
            offset_value= offset->val_int() * (negative_offset ? -1 : 1);
      

      offset_value is a longlong. val_int() of an unsigned 64-bit constant returns its bit pattern, so 18446744073709551614 becomes -2; the item's unsigned_flag is not consulted. MDEV-30682 is a related defect at another site, the frame offset of ROWS BETWEEN n PRECEDING in get_frame_cursor().

      Attachments

        Activity

          People

            psergei Sergei Petrunia
            kehan5800 Ke Han
            Sergei Petrunia Sergei Petrunia
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:

              Git Integration

                Error rendering 'com.xiplink.jira.git.jira_git_plugin:git-issue-webpanel'. Please contact your Jira administrators.