Skip to content

Implement PERIOD_ADD and PERIOD_DIFF functions - #4294

Open
backendArchitect wants to merge 1 commit into
dolthub:mainfrom
backendArchitect:feat/period-add-diff
Open

backendArchitect wants to merge 1 commit into
dolthub:mainfrom
backendArchitect:feat/period-add-diff

Conversation

@backendArchitect

@backendArchitect backendArchitect commented Dec 5, 2026 •

Copy link
Copy Markdown

Fixes: dolthub/dolt#12792

PERIOD_ADD(P, N) and PERIOD_DIFF(P1, P2) were missing, so queries like SELECT PERIOD_DIFF(202612, 202601) failed with function: 'period_diff' not found. The reporter hit this in a WordPress plugin's retention report.

This adds both functions in sql/expression/function/period.go, next to MAKEDATE, following the MySQL 8.4 docs:

  • P is a period in YYMM or YYYYMM format (a number, not a date). Two-digit years below 70 map to 20xx and the rest to 19xx, through the existing types.TwoDigitYear.
  • PERIOD_ADD returns a YYYYMM period, and PERIOD_ADD(0, N) returns 0.
  • PERIOD_DIFF returns the number of months between the two periods (it can be negative).
  • A NULL argument returns NULL. String arguments are coerced like other integer arguments (evalInt64).
  • An invalid period (month part 0 or above 12, or a negative period) returns MySQL's ER_WRONG_ARGUMENTS (1210), Incorrect arguments to period_add. I added this as sql.ErrWrongArguments, mapped to the MySQL error code, because no existing error kind matched it. PERIOD_ADD also returns this error when the result would fall before year 0.
> SELECT PERIOD_DIFF(202612, 202601), PERIOD_ADD(202601, 3);
before: function: 'period_diff' not found
after:  11, 202604

> SELECT PERIOD_ADD(202613, 1);
after:  Incorrect arguments to period_add

Tests:

  • period_test.go: table-driven unit tests for both functions: the examples from the issue and the docs, year rollover, negative months, YYMM input, the 69/70 two-digit year boundary, 0, NULL, string arguments, and invalid months.
  • function_queries.go: engine tests with the same values, plus a PERIOD_DIFF(DATE_FORMAT(...), DATE_FORMAT(...)) query over derived tables (the shape from the report) and the two error cases.

Without the registry.go entries, the new engine tests fail with function: 'period_add' not found. With them, go test ./... passes.

I don't have a MySQL server here, so the invalid-period handling comes from the docs and from how I understand MySQL's valid_period check. I haven't compared it against a live server. That covers erroring on month 0 or 13 and on PERIOD_DIFF(0, x), and returning 0 for PERIOD_ADD(0, N). I'm happy to change it if the team wants a more lenient behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add PERIOD_DIFF() and PERIOD_ADD()

1 participant