Skip to content

Commit a2e8a39

Browse files
authored
feat: expose dialect-aware current-time expression metadata (#2649)
* feat: expose dialect-aware current-time expression metadata * refactor: separate temporal metadata extraction paths
1 parent e244e4b commit a2e8a39

4 files changed

Lines changed: 416 additions & 0 deletions

File tree

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
/*-
2+
* #%L
3+
* JSQLParser library
4+
* %%
5+
* Copyright (C) 2004 - 2026 JSQLParser
6+
* %%
7+
* Dual licensed under GNU LGPL 2.1 or Apache License 2.0
8+
* #L%
9+
*/
10+
package net.sf.jsqlparser.util;
11+
12+
import java.math.BigInteger;
13+
import java.util.Locale;
14+
import java.util.Optional;
15+
import net.sf.jsqlparser.expression.Expression;
16+
import net.sf.jsqlparser.expression.Function;
17+
import net.sf.jsqlparser.expression.LongValue;
18+
import net.sf.jsqlparser.expression.TimeKeyExpression;
19+
import net.sf.jsqlparser.expression.operators.relational.ParenthesedExpressionList;
20+
import net.sf.jsqlparser.parser.AbstractJSqlParser.Dialect;
21+
import net.sf.jsqlparser.schema.Column;
22+
23+
/**
24+
* Read-only metadata for current date/time expressions in PostgreSQL and MySQL. The parser's
25+
* existing TimeKeyExpression, Function and Column nodes are retained. Results are snapshots;
26+
* inspect the expression again after editing its AST. This is not a database range validator.
27+
*/
28+
public final class TemporalExpressionInfo {
29+
30+
public enum Kind {
31+
CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, LOCAL_TIME, LOCAL_TIMESTAMP
32+
}
33+
34+
private final Kind kind;
35+
private final String name;
36+
private final Integer precision;
37+
private final boolean parentheses;
38+
39+
private TemporalExpressionInfo(Kind kind, String name, Integer precision, boolean parentheses) {
40+
this.kind = kind;
41+
this.name = name;
42+
this.precision = precision;
43+
this.parentheses = parentheses;
44+
}
45+
46+
public Kind getKind() {
47+
return kind;
48+
}
49+
50+
/** Returns the original keyword or function name, without argument parentheses. */
51+
public String getName() {
52+
return name;
53+
}
54+
55+
/**
56+
* Returns the explicitly requested fractional precision, or null when omitted. Zero is distinct
57+
* from omission. Database defaults, range checks and precision clamping are not applied.
58+
*/
59+
public Integer getPrecision() {
60+
return precision;
61+
}
62+
63+
public boolean hasParentheses() {
64+
return parentheses;
65+
}
66+
67+
/**
68+
* Recognizes standard current-time spellings and MySQL NOW/CURDATE/CURTIME aliases. MySQL
69+
* LOCALTIME and LOCALTIMESTAMP normalize to CURRENT_TIMESTAMP; PostgreSQL retains their local
70+
* time/time-stamp distinction. Quoted/qualified names, ordinary functions, unsupported dialects
71+
* and expressions outside the supported call shapes return an empty result.
72+
*/
73+
public static Optional<TemporalExpressionInfo> from(Expression source, Dialect dialect) {
74+
if (dialect != Dialect.POSTGRESQL && dialect != Dialect.MYSQL) {
75+
return Optional.empty();
76+
}
77+
Expression expression = unwrap(source);
78+
if (expression instanceof TimeKeyExpression) {
79+
return fromKeyword(((TimeKeyExpression) expression).getStringValue(), dialect);
80+
}
81+
if (expression instanceof Column) {
82+
Column column = (Column) expression;
83+
if (column.getTable() != null && column.getTable().getName() != null) {
84+
return Optional.empty();
85+
}
86+
return create(column.getColumnName(), null, false, dialect);
87+
}
88+
if (expression instanceof Function) {
89+
return fromFunction((Function) expression, dialect);
90+
}
91+
return Optional.empty();
92+
}
93+
94+
private static Expression unwrap(Expression source) {
95+
Expression expression = source;
96+
while (expression instanceof ParenthesedExpressionList
97+
&& ((ParenthesedExpressionList<?>) expression).size() == 1) {
98+
expression = ((ParenthesedExpressionList<?>) expression).get(0);
99+
}
100+
return expression;
101+
}
102+
103+
private static Optional<TemporalExpressionInfo> fromKeyword(String name, Dialect dialect) {
104+
boolean parentheses = name != null && name.endsWith("()");
105+
String keyword = parentheses ? name.substring(0, name.length() - 2) : name;
106+
return create(keyword, null, parentheses, dialect);
107+
}
108+
109+
private static Optional<TemporalExpressionInfo> fromFunction(Function function,
110+
Dialect dialect) {
111+
if (!isPlainCall(function)) {
112+
return Optional.empty();
113+
}
114+
if (function.getParameters() == null || function.getParameters().isEmpty()) {
115+
return create(function.getName(), null, true, dialect);
116+
}
117+
if (function.getParameters().size() != 1
118+
|| !(function.getParameters().get(0) instanceof LongValue)) {
119+
return Optional.empty();
120+
}
121+
BigInteger value = ((LongValue) function.getParameters().get(0)).getBigIntegerValue();
122+
if (value.signum() < 0 || value.bitLength() >= Integer.SIZE) {
123+
return Optional.empty();
124+
}
125+
return create(function.getName(), value.intValue(), true, dialect);
126+
}
127+
128+
private static Optional<TemporalExpressionInfo> create(String name, Integer precision,
129+
boolean parentheses, Dialect dialect) {
130+
if (name == null) {
131+
return Optional.empty();
132+
}
133+
String normalized = name.toUpperCase(Locale.ROOT);
134+
Kind kind = kind(normalized, dialect);
135+
if (kind == null || !validCallShape(normalized, kind, precision, parentheses, dialect)) {
136+
return Optional.empty();
137+
}
138+
return Optional.of(new TemporalExpressionInfo(kind, name, precision, parentheses));
139+
}
140+
141+
private static boolean isPlainCall(Function function) {
142+
return function.getClass() == Function.class
143+
&& function.getMultipartName() != null && function.getMultipartName().size() == 1
144+
&& !function.isEscaped() && !function.isAllColumns() && !function.isDistinct()
145+
&& !function.isUnique() && function.getNamedParameters() == null
146+
&& function.getChainedParameters() == null && function.getAttribute() == null
147+
&& function.getHavingClause() == null && function.getOrderByElements() == null
148+
&& function.getNullHandling() == null && function.getLimit() == null
149+
&& function.getKeep() == null && function.getOnOverflowTruncate() == null
150+
&& function.getExtraKeyword() == null && function.getKeywordArguments() == null;
151+
}
152+
153+
private static Kind kind(String name, Dialect dialect) {
154+
switch (name) {
155+
case "CURRENT_DATE":
156+
return Kind.CURRENT_DATE;
157+
case "CURRENT_TIME":
158+
return Kind.CURRENT_TIME;
159+
case "CURRENT_TIMESTAMP":
160+
case "NOW":
161+
return Kind.CURRENT_TIMESTAMP;
162+
case "LOCALTIME":
163+
return dialect == Dialect.POSTGRESQL ? Kind.LOCAL_TIME : Kind.CURRENT_TIMESTAMP;
164+
case "LOCALTIMESTAMP":
165+
return dialect == Dialect.POSTGRESQL ? Kind.LOCAL_TIMESTAMP
166+
: Kind.CURRENT_TIMESTAMP;
167+
case "CURDATE":
168+
return dialect == Dialect.MYSQL ? Kind.CURRENT_DATE : null;
169+
case "CURTIME":
170+
return dialect == Dialect.MYSQL ? Kind.CURRENT_TIME : null;
171+
default:
172+
return null;
173+
}
174+
}
175+
176+
private static boolean validCallShape(String name, Kind kind, Integer precision,
177+
boolean parentheses, Dialect dialect) {
178+
if (("NOW".equals(name) || "CURDATE".equals(name) || "CURTIME".equals(name))
179+
&& !parentheses) {
180+
return false;
181+
}
182+
if (kind == Kind.CURRENT_DATE && precision != null) {
183+
return false;
184+
}
185+
if (dialect == Dialect.POSTGRESQL) {
186+
return "NOW".equals(name) ? precision == null : parentheses == (precision != null);
187+
}
188+
return true;
189+
}
190+
}

src/site/sphinx/usage.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1243,3 +1243,37 @@ sequences, types or functions as tables. Statement visitors visit comment
12431243
literals, and custom SQL deparsers can replace the explicit relation or literal.
12441244
Feature analysis reports a schema modification. Validation exposes a separate
12451245
``commentOn...`` capability for each additional target kind.
1246+
1247+
Current date/time expression metadata
1248+
=====================================
1249+
1250+
``TemporalExpressionInfo.from(expression, dialect)`` provides a common read-only
1251+
view of MySQL and PostgreSQL current-date/time expressions. It recognizes the
1252+
existing ``TimeKeyExpression``, ``Function`` and ``Column`` representations without
1253+
replacing nodes or changing their SQL rendering:
1254+
1255+
.. code-block:: java
1256+
1257+
PlainSelect select = (PlainSelect) CCJSqlParserUtil.parse(
1258+
"SELECT CURRENT_TIMESTAMP(6)", p -> p.withDialect(Dialect.POSTGRESQL));
1259+
TemporalExpressionInfo info = TemporalExpressionInfo.from(
1260+
select.getSelectItem(0).getExpression(), Dialect.POSTGRESQL).orElseThrow();
1261+
// info.getKind() == TemporalExpressionInfo.Kind.CURRENT_TIMESTAMP
1262+
// info.getPrecision() == 6
1263+
1264+
Import ``TemporalExpressionInfo`` from ``net.sf.jsqlparser.util``. Precision is
1265+
``null`` when omitted, and explicit zero is preserved. ``getName()`` retains the
1266+
original keyword or function name; ``hasParentheses()`` distinguishes bare and
1267+
call forms. Results are snapshots: call ``from`` again after editing an AST.
1268+
1269+
The dialect is significant. MySQL ``LOCALTIME`` and ``LOCALTIMESTAMP`` are aliases
1270+
of ``CURRENT_TIMESTAMP``; PostgreSQL exposes ``LOCAL_TIME`` and
1271+
``LOCAL_TIMESTAMP`` separately. MySQL ``NOW``, ``CURDATE`` and ``CURTIME`` aliases
1272+
are recognized in their function-call forms. PostgreSQL ``now()`` is recognized
1273+
without precision arguments. Quoted or qualified identifiers, unrelated
1274+
expressions and unsupported dialects return ``Optional.empty()``.
1275+
1276+
This API identifies expression metadata rather than performing database
1277+
validation. Precision reports the requested value, without applying defaults,
1278+
server range checks or clamping. For example, PostgreSQL accepts precision 7 with
1279+
a warning and clamps it to 6, whereas MySQL rejects it.
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
/*-
2+
* #%L
3+
* JSQLParser library
4+
* %%
5+
* Copyright (C) 2004 - 2026 JSQLParser
6+
* %%
7+
* Dual licensed under GNU LGPL 2.1 or Apache License 2.0
8+
* #L%
9+
*/
10+
package net.sf.jsqlparser.util;
11+
12+
import static org.junit.jupiter.api.Assertions.assertEquals;
13+
import static org.junit.jupiter.api.Assertions.assertNull;
14+
import static org.junit.jupiter.api.Assertions.assertTrue;
15+
16+
import java.util.List;
17+
import net.sf.jsqlparser.JSQLParserException;
18+
import net.sf.jsqlparser.expression.Expression;
19+
import net.sf.jsqlparser.expression.Function;
20+
import net.sf.jsqlparser.expression.LongValue;
21+
import net.sf.jsqlparser.expression.TimeKeyExpression;
22+
import net.sf.jsqlparser.parser.AbstractJSqlParser.Dialect;
23+
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
24+
import net.sf.jsqlparser.schema.Column;
25+
import net.sf.jsqlparser.statement.select.PlainSelect;
26+
import net.sf.jsqlparser.util.TemporalExpressionInfo.Kind;
27+
import net.sf.jsqlparser.util.deparser.StatementDeParser;
28+
import org.junit.jupiter.api.Test;
29+
import org.junit.jupiter.params.ParameterizedTest;
30+
import org.junit.jupiter.params.provider.CsvFileSource;
31+
import org.junit.jupiter.params.provider.EnumSource;
32+
import org.junit.jupiter.params.provider.ValueSource;
33+
34+
class TemporalExpressionInfoTest {
35+
36+
// Accepted forms from an execution matrix on MySQL 8.4.11 and PostgreSQL 18.6.
37+
@ParameterizedTest
38+
@CsvFileSource(resources = "temporal-expression-cases.tsv", delimiter = '\t')
39+
void recognizesServerAcceptedFormsWithoutChangingTheirAst(Dialect dialect, String expression,
40+
Kind kind, Integer precision) throws JSQLParserException {
41+
PlainSelect select = parse(expression, dialect);
42+
Expression node = select.getSelectItem(0).getExpression();
43+
String original = select.toString();
44+
TemporalExpressionInfo info = TemporalExpressionInfo.from(node, dialect).orElseThrow();
45+
assertEquals(kind, info.getKind());
46+
assertEquals(precision, info.getPrecision());
47+
assertEquals(expression.contains("("), info.hasParentheses());
48+
assertEquals(expression.split("\\(")[0], info.getName());
49+
assertEquals(original, select.toString());
50+
51+
StringBuilder visitor = new StringBuilder();
52+
select.accept(new StatementDeParser(visitor));
53+
for (String sql : List.of(select.toString(), visitor.toString())) {
54+
PlainSelect reparsed = (PlainSelect) CCJSqlParserUtil.parse(sql,
55+
p -> p.withDialect(dialect));
56+
Expression again = reparsed.getSelectItem(0).getExpression();
57+
assertEquals(node.getClass(), again.getClass());
58+
TemporalExpressionInfo after =
59+
TemporalExpressionInfo.from(again, dialect).orElseThrow();
60+
assertEquals(kind, after.getKind());
61+
assertEquals(precision, after.getPrecision());
62+
assertEquals(info.hasParentheses(), after.hasParentheses());
63+
}
64+
}
65+
66+
@Test
67+
void preservesLegacyNodeClassesAndNormalizesTheirMetadata() throws JSQLParserException {
68+
assertEquals(TimeKeyExpression.class,
69+
node("CURRENT_TIMESTAMP", Dialect.POSTGRESQL).getClass());
70+
assertEquals(Function.class,
71+
node("CURRENT_TIMESTAMP(6)", Dialect.POSTGRESQL).getClass());
72+
assertEquals(Column.class, node("LOCALTIME", Dialect.POSTGRESQL).getClass());
73+
assertEquals(Kind.LOCAL_TIME, info("LOCALTIME", Dialect.POSTGRESQL).getKind());
74+
assertEquals(Kind.CURRENT_TIMESTAMP, info("LOCALTIME", Dialect.MYSQL).getKind());
75+
}
76+
77+
@ParameterizedTest
78+
@EnumSource(value = Dialect.class, names = {"MYSQL", "POSTGRESQL"})
79+
void distinguishesOmittedAndZeroPrecisionAndUnwrapsGrouping(Dialect dialect)
80+
throws JSQLParserException {
81+
assertNull(info("CURRENT_TIMESTAMP", dialect).getPrecision());
82+
assertEquals(0, info("CURRENT_TIMESTAMP(0)", dialect).getPrecision());
83+
assertEquals(6, info("((current_timestamp(6)))", dialect).getPrecision());
84+
assertEquals("current_timestamp", info("((current_timestamp(6)))", dialect).getName());
85+
}
86+
87+
@ParameterizedTest
88+
@ValueSource(strings = {"\"LOCALTIME\"", "t.localtime", "t.current_timestamp",
89+
"app.now()", "\"now\"()", "'CURRENT_TIMESTAMP'", "CURRENT_TIMEZONE",
90+
"CURRENT_TIMESTAMP + INTERVAL '1' HOUR", "COALESCE(CURRENT_TIMESTAMP, NULL)",
91+
"CURRENT_TIMESTAMP()", "CURRENT_DATE(1)", "CURRENT_TIMESTAMP('6')",
92+
"CURRENT_TIMESTAMP(1, 2)", "CURRENT_TIMESTAMP(-1)", "NOW(6)", "CURDATE()"})
93+
void doesNotClassifyUnrelatedOrUnsupportedPostgreSqlExpressions(String expression)
94+
throws JSQLParserException {
95+
assertTrue(TemporalExpressionInfo.from(node(expression, Dialect.POSTGRESQL),
96+
Dialect.POSTGRESQL).isEmpty(), expression);
97+
}
98+
99+
@ParameterizedTest
100+
@ValueSource(strings = {"`LOCALTIME`", "\"LOCALTIME\"", "t.localtime", "app.now()",
101+
"'NOW()'", "CURRENT_DATE(6)", "CURRENT_TIMESTAMP(1 + 1)",
102+
"CURRENT_TIMESTAMP(1.5)", "CURRENT_TIMESTAMP(?)", "CURDATE(1)"})
103+
void doesNotClassifyUnrelatedOrUnsupportedMySqlExpressions(String expression)
104+
throws JSQLParserException {
105+
assertTrue(TemporalExpressionInfo.from(node(expression, Dialect.MYSQL),
106+
Dialect.MYSQL).isEmpty(), expression);
107+
}
108+
109+
@Test
110+
void recognizesRequestedPrecisionWithoutApplyingDatabaseRangeRules()
111+
throws JSQLParserException {
112+
// PostgreSQL accepts 7 with a warning and clamps to 6; MySQL rejects 7. Metadata retains
113+
// the requested value, rather than pretending to perform execution-time validation.
114+
assertEquals(7, info("CURRENT_TIMESTAMP(7)", Dialect.POSTGRESQL).getPrecision());
115+
assertEquals(7, info("CURRENT_TIMESTAMP(7)", Dialect.MYSQL).getPrecision());
116+
}
117+
118+
@Test
119+
void returnsSnapshotsAndIgnoresFunctionModifiers() {
120+
Function function = new Function("CURRENT_TIMESTAMP", new LongValue(6));
121+
TemporalExpressionInfo before = TemporalExpressionInfo.from(function, Dialect.MYSQL)
122+
.orElseThrow();
123+
((LongValue) function.getParameters().get(0)).setValue(0);
124+
assertEquals(6, before.getPrecision());
125+
assertEquals(0, TemporalExpressionInfo.from(function, Dialect.MYSQL)
126+
.orElseThrow().getPrecision());
127+
function.setDistinct(true);
128+
assertTrue(TemporalExpressionInfo.from(function, Dialect.MYSQL).isEmpty());
129+
assertTrue(TemporalExpressionInfo.from(new Column("NOW"), Dialect.POSTGRESQL).isEmpty());
130+
assertTrue(TemporalExpressionInfo.from(new Column("CURTIME"), Dialect.MYSQL).isEmpty());
131+
assertTrue(TemporalExpressionInfo.from(null, Dialect.MYSQL).isEmpty());
132+
assertTrue(TemporalExpressionInfo.from(function, Dialect.ORACLE).isEmpty());
133+
}
134+
135+
private static TemporalExpressionInfo info(String expression, Dialect dialect)
136+
throws JSQLParserException {
137+
return TemporalExpressionInfo.from(node(expression, dialect), dialect).orElseThrow();
138+
}
139+
140+
private static Expression node(String expression, Dialect dialect) throws JSQLParserException {
141+
return parse(expression, dialect).getSelectItem(0).getExpression();
142+
}
143+
144+
private static PlainSelect parse(String expression, Dialect dialect)
145+
throws JSQLParserException {
146+
return (PlainSelect) CCJSqlParserUtil.parse("SELECT " + expression,
147+
p -> p.withDialect(dialect));
148+
}
149+
}

0 commit comments

Comments
 (0)