Skip to content

Commit 4e5db42

Browse files
committed
feat: expose dialect-aware current-time expression metadata
1 parent 0036c75 commit 4e5db42

4 files changed

Lines changed: 402 additions & 0 deletions

File tree

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
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+
Expression expression = source;
75+
if (dialect != Dialect.POSTGRESQL && dialect != Dialect.MYSQL) {
76+
return Optional.empty();
77+
}
78+
while (expression instanceof ParenthesedExpressionList
79+
&& ((ParenthesedExpressionList<?>) expression).size() == 1) {
80+
expression = ((ParenthesedExpressionList<?>) expression).get(0);
81+
}
82+
String name;
83+
Integer precision = null;
84+
boolean parentheses = false;
85+
if (expression instanceof TimeKeyExpression) {
86+
name = ((TimeKeyExpression) expression).getStringValue();
87+
if (name != null && name.endsWith("()")) {
88+
parentheses = true;
89+
name = name.substring(0, name.length() - 2);
90+
}
91+
} else if (expression instanceof Column) {
92+
Column column = (Column) expression;
93+
if (column.getTable() != null && column.getTable().getName() != null) {
94+
return Optional.empty();
95+
}
96+
name = column.getColumnName();
97+
} else if (expression instanceof Function && isPlainCall((Function) expression)) {
98+
Function function = (Function) expression;
99+
name = function.getName();
100+
parentheses = true;
101+
if (function.getParameters() != null && !function.getParameters().isEmpty()) {
102+
if (function.getParameters().size() != 1
103+
|| !(function.getParameters().get(0) instanceof LongValue)) {
104+
return Optional.empty();
105+
}
106+
BigInteger value =
107+
((LongValue) function.getParameters().get(0)).getBigIntegerValue();
108+
if (value.signum() < 0 || value.bitLength() >= Integer.SIZE) {
109+
return Optional.empty();
110+
}
111+
precision = value.intValue();
112+
}
113+
} else {
114+
return Optional.empty();
115+
}
116+
if (name == null) {
117+
return Optional.empty();
118+
}
119+
String normalized = name.toUpperCase(Locale.ROOT);
120+
Kind kind = kind(normalized, dialect);
121+
if (kind == null || !validCallShape(normalized, kind, precision, parentheses, dialect)) {
122+
return Optional.empty();
123+
}
124+
return Optional.of(new TemporalExpressionInfo(kind, name, precision, parentheses));
125+
}
126+
127+
private static boolean isPlainCall(Function function) {
128+
return function.getClass() == Function.class
129+
&& function.getMultipartName() != null && function.getMultipartName().size() == 1
130+
&& !function.isEscaped() && !function.isAllColumns() && !function.isDistinct()
131+
&& !function.isUnique() && function.getNamedParameters() == null
132+
&& function.getChainedParameters() == null && function.getAttribute() == null
133+
&& function.getHavingClause() == null && function.getOrderByElements() == null
134+
&& function.getNullHandling() == null && function.getLimit() == null
135+
&& function.getKeep() == null && function.getOnOverflowTruncate() == null
136+
&& function.getExtraKeyword() == null && function.getKeywordArguments() == null;
137+
}
138+
139+
private static Kind kind(String name, Dialect dialect) {
140+
switch (name) {
141+
case "CURRENT_DATE":
142+
return Kind.CURRENT_DATE;
143+
case "CURRENT_TIME":
144+
return Kind.CURRENT_TIME;
145+
case "CURRENT_TIMESTAMP":
146+
case "NOW":
147+
return Kind.CURRENT_TIMESTAMP;
148+
case "LOCALTIME":
149+
return dialect == Dialect.POSTGRESQL ? Kind.LOCAL_TIME : Kind.CURRENT_TIMESTAMP;
150+
case "LOCALTIMESTAMP":
151+
return dialect == Dialect.POSTGRESQL ? Kind.LOCAL_TIMESTAMP
152+
: Kind.CURRENT_TIMESTAMP;
153+
case "CURDATE":
154+
return dialect == Dialect.MYSQL ? Kind.CURRENT_DATE : null;
155+
case "CURTIME":
156+
return dialect == Dialect.MYSQL ? Kind.CURRENT_TIME : null;
157+
default:
158+
return null;
159+
}
160+
}
161+
162+
private static boolean validCallShape(String name, Kind kind, Integer precision,
163+
boolean parentheses, Dialect dialect) {
164+
if (("NOW".equals(name) || "CURDATE".equals(name) || "CURTIME".equals(name))
165+
&& !parentheses) {
166+
return false;
167+
}
168+
if (kind == Kind.CURRENT_DATE && precision != null) {
169+
return false;
170+
}
171+
if (dialect == Dialect.POSTGRESQL) {
172+
return "NOW".equals(name) ? precision == null : parentheses == (precision != null);
173+
}
174+
return true;
175+
}
176+
}

src/site/sphinx/usage.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1212,3 +1212,37 @@ sequences, types or functions as tables. Statement visitors visit comment
12121212
literals, and custom SQL deparsers can replace the explicit relation or literal.
12131213
Feature analysis reports a schema modification. Validation exposes a separate
12141214
``commentOn...`` capability for each additional target kind.
1215+
1216+
Current date/time expression metadata
1217+
=====================================
1218+
1219+
``TemporalExpressionInfo.from(expression, dialect)`` provides a common read-only
1220+
view of MySQL and PostgreSQL current-date/time expressions. It recognizes the
1221+
existing ``TimeKeyExpression``, ``Function`` and ``Column`` representations without
1222+
replacing nodes or changing their SQL rendering:
1223+
1224+
.. code-block:: java
1225+
1226+
PlainSelect select = (PlainSelect) CCJSqlParserUtil.parse(
1227+
"SELECT CURRENT_TIMESTAMP(6)", p -> p.withDialect(Dialect.POSTGRESQL));
1228+
TemporalExpressionInfo info = TemporalExpressionInfo.from(
1229+
select.getSelectItem(0).getExpression(), Dialect.POSTGRESQL).orElseThrow();
1230+
// info.getKind() == TemporalExpressionInfo.Kind.CURRENT_TIMESTAMP
1231+
// info.getPrecision() == 6
1232+
1233+
Import ``TemporalExpressionInfo`` from ``net.sf.jsqlparser.util``. Precision is
1234+
``null`` when omitted, and explicit zero is preserved. ``getName()`` retains the
1235+
original keyword or function name; ``hasParentheses()`` distinguishes bare and
1236+
call forms. Results are snapshots: call ``from`` again after editing an AST.
1237+
1238+
The dialect is significant. MySQL ``LOCALTIME`` and ``LOCALTIMESTAMP`` are aliases
1239+
of ``CURRENT_TIMESTAMP``; PostgreSQL exposes ``LOCAL_TIME`` and
1240+
``LOCAL_TIMESTAMP`` separately. MySQL ``NOW``, ``CURDATE`` and ``CURTIME`` aliases
1241+
are recognized in their function-call forms. PostgreSQL ``now()`` is recognized
1242+
without precision arguments. Quoted or qualified identifiers, unrelated
1243+
expressions and unsupported dialects return ``Optional.empty()``.
1244+
1245+
This API identifies expression metadata rather than performing database
1246+
validation. Precision reports the requested value, without applying defaults,
1247+
server range checks or clamping. For example, PostgreSQL accepts precision 7 with
1248+
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)