expressionVisitor, S context) {
+ return expressionVisitor.visit(this, context);
+ }
+}
diff --git a/src/main/java/net/sf/jsqlparser/expression/MySQLIndexHint.java b/src/main/java/net/sf/jsqlparser/expression/MySQLIndexHint.java
index 7360a4b2e5..17044a9fb3 100644
--- a/src/main/java/net/sf/jsqlparser/expression/MySQLIndexHint.java
+++ b/src/main/java/net/sf/jsqlparser/expression/MySQLIndexHint.java
@@ -12,15 +12,35 @@
import java.io.Serializable;
import java.util.List;
+/**
+ * A MySQL index hint after a table reference:
+ * {@code {USE|IGNORE|FORCE} {INDEX|KEY} [FOR {JOIN|ORDER BY|GROUP BY}] (index_list)}.
+ *
+ * A table may carry several hints, see {@code Table.getIndexHints()}. {@code USE INDEX ()} has an
+ * empty index list.
+ */
public class MySQLIndexHint implements Serializable {
private final String action;
private final String indexQualifier;
+ private final Scope scope;
private final List indexNames;
public MySQLIndexHint(String action, String indexQualifier, List indexNames) {
+ this(action, indexQualifier, null, indexNames);
+ }
+
+ /**
+ * @param action {@code USE}, {@code IGNORE} or {@code FORCE}
+ * @param indexQualifier {@code INDEX} or {@code KEY}
+ * @param scope the {@code FOR JOIN|ORDER BY|GROUP BY} scope, or {@code null} for every use
+ * @param indexNames the index names, empty for {@code USE INDEX ()}
+ */
+ public MySQLIndexHint(String action, String indexQualifier, Scope scope,
+ List indexNames) {
this.action = action;
this.indexQualifier = indexQualifier;
+ this.scope = scope;
this.indexNames = indexNames;
}
@@ -32,22 +52,53 @@ public String getIndexQualifier() {
return indexQualifier;
}
+ /**
+ * Returns the part of the query the hint applies to, or {@code null} when no {@code FOR} clause
+ * was given.
+ */
+ public Scope getScope() {
+ return scope;
+ }
+
public List getIndexNames() {
return indexNames;
}
- @Override
- public String toString() {
- // use|ignore|force key|index (index1,...,indexN)
- StringBuilder buffer = new StringBuilder();
- buffer.append(" ").append(action).append(" ").append(indexQualifier).append(" (");
+ /** Appends {@code " USE INDEX [FOR scope] (i1,i2)"}, with a leading space. */
+ public StringBuilder appendTo(StringBuilder builder) {
+ // use|ignore|force key|index [for join|order by|group by] (index1,...,indexN)
+ builder.append(" ").append(action).append(" ").append(indexQualifier);
+ if (scope != null) {
+ builder.append(" FOR ").append(scope.getKeywords());
+ }
+ builder.append(" (");
for (int i = 0; i < indexNames.size(); i++) {
if (i > 0) {
- buffer.append(",");
+ builder.append(",");
}
- buffer.append(indexNames.get(i));
+ builder.append(indexNames.get(i));
+ }
+ return builder.append(")");
+ }
+
+ @Override
+ public String toString() {
+ return appendTo(new StringBuilder()).toString();
+ }
+
+ /** The {@code FOR} clause of an index hint. */
+ public enum Scope {
+ JOIN("JOIN"), ORDER_BY("ORDER BY"), GROUP_BY("GROUP BY");
+
+ private final String keywords;
+
+ Scope(String keywords) {
+ this.keywords = keywords;
+ }
+
+ /** Returns the keywords after {@code FOR}, for example {@code ORDER BY}. */
+ public String getKeywords() {
+ return keywords;
}
- buffer.append(")");
- return buffer.toString();
}
}
diff --git a/src/main/java/net/sf/jsqlparser/expression/RangeExpression.java b/src/main/java/net/sf/jsqlparser/expression/RangeExpression.java
index dd05827d64..326f5b7da5 100644
--- a/src/main/java/net/sf/jsqlparser/expression/RangeExpression.java
+++ b/src/main/java/net/sf/jsqlparser/expression/RangeExpression.java
@@ -14,6 +14,7 @@
public class RangeExpression extends ASTNodeAccessImpl implements Expression {
private Expression startExpression;
private Expression endExpression;
+ private Expression stepExpression;
public RangeExpression(Expression startExpression, Expression endExpression) {
this.startExpression = startExpression;
@@ -38,9 +39,42 @@ public RangeExpression setEndExpression(Expression endExpression) {
return this;
}
+ public Expression getStepExpression() {
+ return stepExpression;
+ }
+
+ public RangeExpression setStepExpression(Expression stepExpression) {
+ this.stepExpression = stepExpression;
+ return this;
+ }
+
+ public RangeExpression withStepExpression(Expression stepExpression) {
+ return setStepExpression(stepExpression);
+ }
+
+ /**
+ * Renders {@code [start]:[end][:step]}, a missing end before a step as DuckDB's {@code -}.
+ */
+ public static String toString(Expression start, Expression end, Expression step) {
+ StringBuilder builder = new StringBuilder();
+ if (start != null) {
+ builder.append(start);
+ }
+ builder.append(":");
+ if (end != null) {
+ builder.append(end);
+ } else if (step != null) {
+ builder.append("-");
+ }
+ if (step != null) {
+ builder.append(":").append(step);
+ }
+ return builder.toString();
+ }
+
@Override
public String toString() {
- return startExpression + ":" + endExpression;
+ return toString(startExpression, endExpression, stepExpression);
}
@Override
diff --git a/src/main/java/net/sf/jsqlparser/expression/SignedExpression.java b/src/main/java/net/sf/jsqlparser/expression/SignedExpression.java
index 725d449e89..43c92e29b3 100644
--- a/src/main/java/net/sf/jsqlparser/expression/SignedExpression.java
+++ b/src/main/java/net/sf/jsqlparser/expression/SignedExpression.java
@@ -54,7 +54,23 @@ public T accept(ExpressionVisitor expressionVisitor, S context) {
@Override
public String toString() {
- return getSign() + expression.toString();
+ String operand = expression.toString();
+ return getSign() + (needsSpaceBefore(operand) ? " " : "") + operand;
+ }
+
+ /**
+ * Whether the sign must be separated from an operand starting with {@code firstChar}: "- -1"
+ * must not become the line comment "--1", nor "~ -a" or "~ ~a" a single operator such as "~-"
+ * or the LIKE operator "~~", as DuckDB and PostgreSQL read a run of signs containing {@code ~}.
+ */
+ public boolean needsSpaceBefore(char firstChar) {
+ boolean signedOperand = firstChar == '+' || firstChar == '-' || firstChar == '~';
+ return sign == '-' && firstChar == '-' || sign == '~' && signedOperand
+ || firstChar == '~' && (sign == '+' || sign == '-');
+ }
+
+ private boolean needsSpaceBefore(String operand) {
+ return !operand.isEmpty() && needsSpaceBefore(operand.charAt(0));
}
public SignedExpression withSign(char sign) {
diff --git a/src/main/java/net/sf/jsqlparser/expression/SpannerInterleaveIn.java b/src/main/java/net/sf/jsqlparser/expression/SpannerInterleaveIn.java
index 4dcb0aa7f5..dc5e56d208 100644
--- a/src/main/java/net/sf/jsqlparser/expression/SpannerInterleaveIn.java
+++ b/src/main/java/net/sf/jsqlparser/expression/SpannerInterleaveIn.java
@@ -9,13 +9,13 @@
*/
package net.sf.jsqlparser.expression;
-import java.util.Locale;
-import net.sf.jsqlparser.schema.Table;
-
+import java.io.Serializable;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
+import net.sf.jsqlparser.schema.Table;
-public class SpannerInterleaveIn {
+public class SpannerInterleaveIn implements Serializable {
private Table table;
private OnDelete onDelete;
diff --git a/src/main/java/net/sf/jsqlparser/expression/StringValue.java b/src/main/java/net/sf/jsqlparser/expression/StringValue.java
index 46bf58810a..55f44fee94 100644
--- a/src/main/java/net/sf/jsqlparser/expression/StringValue.java
+++ b/src/main/java/net/sf/jsqlparser/expression/StringValue.java
@@ -9,6 +9,8 @@
*/
package net.sf.jsqlparser.expression;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@@ -22,9 +24,35 @@ public final class StringValue extends ASTNodeAccessImpl implements Expression {
public static final List ALLOWED_PREFIXES =
Arrays.asList("N", "U", "E", "R", "B", "RB", "_utf8", "Q");
+
+ /** The prefix of a PostgreSQL Unicode escape string, as in {@code U&'\0041'}. */
+ private static final String UNICODE_ESCAPE_PREFIX = "U&";
+
+ /**
+ * How a backslash in the literal body was read. The parser records the escaping of the
+ * configuration that lexed the literal; constructed values default to {@link #STANDARD}.
+ */
+ public enum Escaping {
+ /** Only a doubled quote character is an escape, as in standard SQL. */
+ STANDARD,
+ /** MySQL/MariaDB backslash escapes, for example {@code \n}, {@code \'} and {@code \\}. */
+ MYSQL_BACKSLASH,
+ /** PostgreSQL escape string escapes, for example {@code E'\n'} and {@code E'\x41'}. */
+ POSTGRESQL_ESCAPE_STRING,
+ /**
+ * PostgreSQL Unicode escapes of a {@code U&'...'} string: the escape character followed by
+ * four hexadecimal digits or by {@code +} and six, and a doubled escape character. The
+ * escape character is a backslash unless {@link #getUnicodeEscapeCharacter()} names another
+ * one.
+ */
+ POSTGRESQL_UNICODE_ESCAPE
+ }
+
private String value = "";
private String prefix = null;
private String quoteStr = "'";
+ private Escaping escaping = Escaping.STANDARD;
+ private Character unicodeEscapeCharacter = null;
public StringValue() {
// empty constructor
@@ -53,7 +81,18 @@ public StringValue(String escapedValue) {
return;
}
+ if (readUnicodeEscapeString(escapedValue)) {
+ return;
+ }
+
if (escapedValue.length() > 2) {
+ // Databricks raw literal R"..."
+ if (escapedValue.regionMatches(true, 0, "R\"", 0, 2) && escapedValue.endsWith("\"")) {
+ prefix = "R";
+ quoteStr = "\"";
+ value = escapedValue.substring(2, escapedValue.length() - 1);
+ return;
+ }
for (String p : ALLOWED_PREFIXES) {
if (escapedValue.length() > p.length()
&& escapedValue.substring(0, p.length()).equalsIgnoreCase(p)
@@ -68,6 +107,46 @@ public StringValue(String escapedValue) {
value = escapedValue;
}
+ /**
+ * Reads {@code U&'body'} with an optional {@code UESCAPE 'c'} clause. Returns false, leaving
+ * this value unchanged, when the text has another shape.
+ */
+ private boolean readUnicodeEscapeString(String text) {
+ if (!text.regionMatches(true, 0, UNICODE_ESCAPE_PREFIX + "'", 0, 3)) {
+ return false;
+ }
+ int close = 3;
+ while (close < text.length()) {
+ if (text.charAt(close) != '\'') {
+ close++;
+ } else if (close + 1 < text.length() && text.charAt(close + 1) == '\'') {
+ close += 2;
+ } else {
+ break;
+ }
+ }
+ if (close >= text.length()) {
+ return false;
+ }
+ String clause = text.substring(close + 1).trim();
+ Character escape = null;
+ if (!clause.isEmpty()) {
+ if (!clause.regionMatches(true, 0, "UESCAPE", 0, 7)) {
+ return false;
+ }
+ String quoted = clause.substring(7).trim();
+ if (quoted.length() != 3 || quoted.charAt(0) != '\'' || quoted.charAt(2) != '\'') {
+ return false;
+ }
+ escape = quoted.charAt(1);
+ }
+ prefix = UNICODE_ESCAPE_PREFIX;
+ value = text.substring(3, close);
+ escaping = Escaping.POSTGRESQL_UNICODE_ESCAPE;
+ unicodeEscapeCharacter = escape;
+ return true;
+ }
+
/**
* Returns the opening PostgreSQL dollar-quote delimiter, or null if there is none. A tag
* follows unquoted identifier rules, excluding dollar signs. This method does not require the
@@ -119,19 +198,377 @@ public StringValue setQuoteStr(String quoteStr) {
return this;
}
+ public Escaping getEscaping() {
+ return escaping;
+ }
+
+ public void setEscaping(Escaping escaping) {
+ this.escaping = escaping == null ? Escaping.STANDARD : escaping;
+ }
+
+ public StringValue withEscaping(Escaping escaping) {
+ setEscaping(escaping);
+ return this;
+ }
+
+ /**
+ * Returns the escape character named by the {@code UESCAPE} clause of a PostgreSQL Unicode
+ * escape string, or null when the literal has no such clause and the escape character is a
+ * backslash.
+ */
+ public Character getUnicodeEscapeCharacter() {
+ return unicodeEscapeCharacter;
+ }
+
+ /**
+ * Sets the escape character rendered as {@code UESCAPE 'c'} after the literal; null removes the
+ * clause. It applies to {@link Escaping#POSTGRESQL_UNICODE_ESCAPE} values, whose
+ * {@link #getNotExcapedValue()} rejects a character that PostgreSQL rejects.
+ */
+ public void setUnicodeEscapeCharacter(Character unicodeEscapeCharacter) {
+ this.unicodeEscapeCharacter = unicodeEscapeCharacter;
+ }
+
+ public StringValue withUnicodeEscapeCharacter(Character unicodeEscapeCharacter) {
+ setUnicodeEscapeCharacter(unicodeEscapeCharacter);
+ return this;
+ }
+
+ /**
+ * Returns the literal's characters with its escapes resolved: a doubled quote character and,
+ * depending on {@link #getEscaping()}, backslash or Unicode escape sequences. PostgreSQL octal
+ * and hexadecimal escapes denote bytes, which are decoded as UTF-8. Dollar-quoted bodies are
+ * returned unchanged.
+ *
+ * @throws IllegalArgumentException if a {@link Escaping#POSTGRESQL_UNICODE_ESCAPE} value has an
+ * escape that PostgreSQL rejects, or a {@link Escaping#POSTGRESQL_ESCAPE_STRING} value
+ * has a Unicode escape that PostgreSQL rejects; the parser rejects such literals
+ */
public String getNotExcapedValue() {
if (quoteStr != null && quoteStr.startsWith("$")) {
return value;
}
- StringBuilder buffer = new StringBuilder(value);
- int index = 0;
- int deletesNum = 0;
- while ((index = value.indexOf("''", index)) != -1) {
- buffer.deleteCharAt(index - deletesNum);
- index += 2;
- deletesNum++;
+ char quote = "\"".equals(quoteStr) ? '"' : '\'';
+ if (escaping == Escaping.POSTGRESQL_UNICODE_ESCAPE) {
+ return unescapeUnicode(value, quote,
+ unicodeEscapeCharacter == null ? '\\' : unicodeEscapeCharacter);
+ }
+ Unescaped result = new Unescaped(value.length());
+ int i = 0;
+ while (i < value.length()) {
+ char c = value.charAt(i);
+ if (c == '\\' && escaping != Escaping.STANDARD && i + 1 < value.length()) {
+ i = escaping == Escaping.MYSQL_BACKSLASH
+ ? appendMySqlEscape(result, value.charAt(i + 1), i + 1)
+ : appendPostgresEscape(result, value, i + 1);
+ } else if (c == quote && i + 1 < value.length() && value.charAt(i + 1) == quote) {
+ result.append(quote);
+ i += 2;
+ } else {
+ result.append(c);
+ i++;
+ }
+ }
+ return result.toString();
+ }
+
+ /** Appends the MySQL escape {@code c} at {@code index} and returns the index after it. */
+ private static int appendMySqlEscape(Unescaped result, char c, int index) {
+ switch (c) {
+ case '0':
+ result.append('\0');
+ break;
+ case 'b':
+ result.append('\b');
+ break;
+ case 'n':
+ result.append('\n');
+ break;
+ case 'r':
+ result.append('\r');
+ break;
+ case 't':
+ result.append('\t');
+ break;
+ case 'Z':
+ result.append((char) 0x1A);
+ break;
+ case '%':
+ case '_':
+ // kept with the backslash, so that LIKE patterns still match them literally
+ result.append('\\');
+ result.append(c);
+ break;
+ default:
+ result.append(c);
+ }
+ return index + 1;
+ }
+
+ /** Appends the PostgreSQL escape string escape at {@code index}; returns the next index. */
+ private static int appendPostgresEscape(Unescaped result, String text, int index) {
+ char c = text.charAt(index);
+ switch (c) {
+ case 'b':
+ result.append('\b');
+ return index + 1;
+ case 'f':
+ result.append('\f');
+ return index + 1;
+ case 'n':
+ result.append('\n');
+ return index + 1;
+ case 'r':
+ result.append('\r');
+ return index + 1;
+ case 't':
+ result.append('\t');
+ return index + 1;
+ case 'x':
+ return appendByte(result, text, index + 1, 16, 1, 2, c);
+ case 'u':
+ return appendCodePoint(result, text, index, 4);
+ case 'U':
+ return appendCodePoint(result, text, index, 8);
+ default:
+ if (c >= '0' && c <= '7') {
+ return appendByte(result, text, index, 8, 1, 3, c);
+ }
+ result.append(c);
+ return index + 1;
+ }
+ }
+
+ /**
+ * Appends the byte spelled by {@code min} to {@code max} digits at {@code start}, or
+ * {@code fallback} when fewer digits follow, and returns the next index.
+ */
+ private static int appendByte(Unescaped result, String text, int start, int radix, int min,
+ int max, char fallback) {
+ int end = start;
+ while (end < text.length() && end - start < max
+ && Character.digit(text.charAt(end), radix) >= 0) {
+ end++;
+ }
+ if (end - start < min) {
+ result.append(fallback);
+ return start;
+ }
+ result.appendByte(Integer.parseInt(text.substring(start, end), radix));
+ return end;
+ }
+
+ /**
+ * Appends the code point spelled by exactly {@code digits} hexadecimal digits after the escape
+ * letter at {@code index} and returns the next index. As in a Unicode escape string, the code
+ * point must be valid and a UTF-16 surrogate pair must be written as two consecutive escapes.
+ */
+ private static int appendCodePoint(Unescaped result, String text, int index, int digits) {
+ int start = index + 1;
+ int end = start + digits;
+ long codePoint = parseHex(text, start, end);
+ if (codePoint < 0) {
+ throw new IllegalArgumentException("invalid Unicode escape at position " + (index - 1)
+ + ": Unicode escapes must be \\u followed by 4 or \\U by 8 hexadecimal digits");
+ }
+ if (codePoint == 0 || codePoint > Character.MAX_CODE_POINT) {
+ throw new IllegalArgumentException(
+ "invalid Unicode escape value at position " + (index - 1));
+ }
+ result.appendCodePoint((int) codePoint, index - 1);
+ return end;
+ }
+
+ /**
+ * Resolves PostgreSQL Unicode escapes the way the server does: {@code escape} followed by four
+ * hexadecimal digits, or by {@code +} and six, names a code point, and a UTF-16 surrogate pair
+ * must be written as two consecutive escapes. A doubled escape or quote character stands for
+ * itself.
+ */
+ private static String unescapeUnicode(String text, char quote, char escape) {
+ checkUnicodeEscapeCharacter(escape);
+ UnicodeUnescaped result = new UnicodeUnescaped(text.length());
+ int i = 0;
+ while (i < text.length()) {
+ char c = text.charAt(i);
+ boolean doubled = i + 1 < text.length() && text.charAt(i + 1) == c;
+ if (c == escape && !doubled) {
+ i = appendUnicodeEscape(result, text, i, escape);
+ } else {
+ result.append(c, i);
+ i += doubled && (c == escape || c == quote) ? 2 : 1;
+ }
+ }
+ return result.finish(text.length());
+ }
+
+ private static void checkUnicodeEscapeCharacter(char escape) {
+ if (escape > 0x7F || isHexDigit(escape) || "+'\" \t\n\r\f\u000B".indexOf(escape) >= 0) {
+ throw new IllegalArgumentException("invalid Unicode escape character '" + escape + "'");
+ }
+ }
+
+ /**
+ * Appends the code point of the escape at {@code position}, {@code escape} followed by four
+ * hexadecimal digits or by {@code +} and six, and returns the next index.
+ */
+ private static int appendUnicodeEscape(UnicodeUnescaped result, String text, int position,
+ char escape) {
+ boolean plus = position + 1 < text.length() && text.charAt(position + 1) == '+';
+ int start = plus ? position + 2 : position + 1;
+ int end = start + (plus ? 6 : 4);
+ long codePoint = parseHex(text, start, end);
+ if (codePoint < 0) {
+ throw new IllegalArgumentException("invalid Unicode escape at position " + position
+ + ": Unicode escapes must be " + escape + "XXXX or " + escape + "+XXXXXX");
+ }
+ if (codePoint == 0 || codePoint > Character.MAX_CODE_POINT) {
+ throw new IllegalArgumentException(
+ "invalid Unicode escape value at position " + position);
+ }
+ result.appendCodePoint((int) codePoint, position);
+ return end;
+ }
+
+ private static IllegalArgumentException invalidSurrogatePair(int position) {
+ return new IllegalArgumentException(
+ "invalid Unicode surrogate pair at position " + position);
+ }
+
+ private static boolean isHexDigit(char c) {
+ return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F';
+ }
+
+ /** Returns the ASCII hexadecimal number spelled by text[start, end), or -1. */
+ private static long parseHex(String text, int start, int end) {
+ if (end > text.length()) {
+ return -1;
+ }
+ long number = 0;
+ for (int i = start; i < end; i++) {
+ char c = text.charAt(i);
+ if (!isHexDigit(c)) {
+ return -1;
+ }
+ number = number * 16 + Character.digit(c, 16);
+ }
+ return number;
+ }
+
+ /**
+ * Collects unescaped characters; consecutive escaped bytes are decoded as UTF-8. A UTF-16
+ * surrogate pair must be written as two consecutive Unicode escapes, as PostgreSQL requires.
+ */
+ private static final class Unescaped {
+ private final StringBuilder chars;
+ private final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ private char highSurrogate;
+ private int highSurrogatePosition;
+
+ Unescaped(int capacity) {
+ chars = new StringBuilder(capacity);
+ }
+
+ void append(char c) {
+ requireNoPendingSurrogate();
+ flushBytes();
+ chars.append(c);
+ }
+
+ /** Appends the code point of the Unicode escape at {@code position}. */
+ void appendCodePoint(int codePoint, int position) {
+ flushBytes();
+ if (codePoint >= Character.MIN_LOW_SURROGATE
+ && codePoint <= Character.MAX_LOW_SURROGATE) {
+ if (highSurrogate == 0) {
+ throw invalidSurrogatePair(position);
+ }
+ chars.appendCodePoint(Character.toCodePoint(highSurrogate, (char) codePoint));
+ highSurrogate = 0;
+ return;
+ }
+ requireNoPendingSurrogate();
+ if (codePoint >= Character.MIN_HIGH_SURROGATE
+ && codePoint <= Character.MAX_HIGH_SURROGATE) {
+ highSurrogate = (char) codePoint;
+ highSurrogatePosition = position;
+ } else {
+ chars.appendCodePoint(codePoint);
+ }
+ }
+
+ void appendByte(int value) {
+ requireNoPendingSurrogate();
+ bytes.write(value);
+ }
+
+ private void flushBytes() {
+ if (bytes.size() > 0) {
+ chars.append(new String(bytes.toByteArray(), StandardCharsets.UTF_8));
+ bytes.reset();
+ }
+ }
+
+ private void requireNoPendingSurrogate() {
+ if (highSurrogate != 0) {
+ throw invalidSurrogatePair(highSurrogatePosition);
+ }
+ }
+
+ @Override
+ public String toString() {
+ requireNoPendingSurrogate();
+ flushBytes();
+ return chars.toString();
+ }
+ }
+
+ /**
+ * Collects resolved Unicode escapes. A UTF-16 surrogate pair must be written as two consecutive
+ * escapes, as PostgreSQL requires.
+ */
+ private static final class UnicodeUnescaped {
+ private final StringBuilder chars;
+ private char highSurrogate;
+
+ UnicodeUnescaped(int capacity) {
+ chars = new StringBuilder(capacity);
+ }
+
+ void append(char c, int position) {
+ requireNoPendingSurrogate(position);
+ chars.append(c);
+ }
+
+ void appendCodePoint(int codePoint, int position) {
+ if (codePoint >= Character.MIN_LOW_SURROGATE
+ && codePoint <= Character.MAX_LOW_SURROGATE) {
+ if (highSurrogate == 0) {
+ throw invalidSurrogatePair(position);
+ }
+ chars.appendCodePoint(Character.toCodePoint(highSurrogate, (char) codePoint));
+ highSurrogate = 0;
+ return;
+ }
+ requireNoPendingSurrogate(position);
+ if (codePoint >= Character.MIN_HIGH_SURROGATE
+ && codePoint <= Character.MAX_HIGH_SURROGATE) {
+ highSurrogate = (char) codePoint;
+ } else {
+ chars.appendCodePoint(codePoint);
+ }
+ }
+
+ String finish(int position) {
+ requireNoPendingSurrogate(position);
+ return chars.toString();
+ }
+
+ private void requireNoPendingSurrogate(int position) {
+ if (highSurrogate != 0) {
+ throw invalidSurrogatePair(position);
+ }
}
- return buffer.toString();
}
@Override
@@ -141,7 +578,10 @@ public T accept(ExpressionVisitor expressionVisitor, S context) {
@Override
public String toString() {
- return (prefix != null ? prefix : "") + quoteStr + value + quoteStr;
+ String unicodeEscape = unicodeEscapeCharacter != null
+ ? " UESCAPE '" + unicodeEscapeCharacter + "'"
+ : "";
+ return (prefix != null ? prefix : "") + quoteStr + value + quoteStr + unicodeEscape;
}
public StringValue withPrefix(String prefix) {
diff --git a/src/main/java/net/sf/jsqlparser/expression/TimezoneExpression.java b/src/main/java/net/sf/jsqlparser/expression/TimezoneExpression.java
index a67572acea..6959549879 100644
--- a/src/main/java/net/sf/jsqlparser/expression/TimezoneExpression.java
+++ b/src/main/java/net/sf/jsqlparser/expression/TimezoneExpression.java
@@ -14,11 +14,13 @@
import java.util.Arrays;
import java.util.List;
+import java.util.function.Consumer;
public class TimezoneExpression extends ASTNodeAccessImpl implements Expression {
private final ExpressionList timezoneExpressions = new ExpressionList<>();
private Expression leftExpression;
+ private boolean atLocal;
public TimezoneExpression() {
leftExpression = null;
@@ -51,13 +53,37 @@ public void addTimezoneExpression(Expression... timezoneExpr) {
this.timezoneExpressions.addAll(Arrays.asList(timezoneExpr));
}
- @Override
- public String toString() {
- StringBuilder returnValue = new StringBuilder(leftExpression.toString());
+ /**
+ * Whether the expression ends with {@code AT LOCAL}, which converts to the session time zone.
+ * It follows the {@code AT TIME ZONE} conversions of this expression, if there are any.
+ */
+ public boolean isAtLocal() {
+ return atLocal;
+ }
+
+ public TimezoneExpression setAtLocal(boolean atLocal) {
+ this.atLocal = atLocal;
+ return this;
+ }
+
+ /**
+ * Appends the expression, rendering the operand and each time zone through the renderer.
+ */
+ public StringBuilder appendTo(StringBuilder builder, Consumer expressionRenderer) {
+ expressionRenderer.accept(leftExpression);
for (Expression expr : timezoneExpressions) {
- returnValue.append(" AT TIME ZONE ").append(expr.toString());
+ builder.append(" AT TIME ZONE ");
+ expressionRenderer.accept(expr);
+ }
+ if (atLocal) {
+ builder.append(" AT LOCAL");
}
+ return builder;
+ }
- return returnValue.toString();
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ return appendTo(builder, builder::append).toString();
}
}
diff --git a/src/main/java/net/sf/jsqlparser/expression/WindowDefinition.java b/src/main/java/net/sf/jsqlparser/expression/WindowDefinition.java
index 2996821cf2..cbf6253548 100644
--- a/src/main/java/net/sf/jsqlparser/expression/WindowDefinition.java
+++ b/src/main/java/net/sf/jsqlparser/expression/WindowDefinition.java
@@ -23,6 +23,7 @@ public class WindowDefinition implements Serializable {
final PartitionByClause partitionBy = new PartitionByClause();
WindowElement windowElement = null;
private String windowName;
+ private String baseWindowName;
public OrderByClause getOrderBy() {
return orderBy;
@@ -61,6 +62,31 @@ public void setPartitionExpressionList(ExpressionList partitionExpre
partitionBy.setExpressions(partitionExpressionList, brackets);
}
+ /** DuckDB: the window this one extends, as w in OVER (w ORDER BY b), or {@code null}. */
+ public String getBaseWindowName() {
+ return baseWindowName;
+ }
+
+ public WindowDefinition setBaseWindowName(String baseWindowName) {
+ this.baseWindowName = baseWindowName;
+ return this;
+ }
+
+ /** Appends the base window name, separated from any following part. */
+ public void appendBaseWindowNameTo(StringBuilder builder) {
+ if (baseWindowName != null) {
+ builder.append(baseWindowName);
+ boolean more = partitionBy.getPartitionExpressionList() != null
+ && !partitionBy.getPartitionExpressionList().isEmpty()
+ || orderBy.getOrderByElements() != null
+ && !orderBy.getOrderByElements().isEmpty()
+ || windowElement != null;
+ if (more) {
+ builder.append(' ');
+ }
+ }
+ }
+
public String getWindowName() {
return windowName;
}
@@ -105,6 +131,7 @@ public String toString() {
b.append(windowName).append(" AS ");
}
b.append("(");
+ appendBaseWindowNameTo(b);
partitionBy.toStringPartitionBy(b);
orderBy.toStringOrderByElements(b);
diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Exponentiation.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Exponentiation.java
new file mode 100644
index 0000000000..321e014879
--- /dev/null
+++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Exponentiation.java
@@ -0,0 +1,44 @@
+/*-
+ * #%L
+ * JSQLParser library
+ * %%
+ * Copyright (C) 2004 - 2026 JSQLParser
+ * %%
+ * Dual licensed under GNU LGPL 2.1 or Apache License 2.0
+ * #L%
+ */
+package net.sf.jsqlparser.expression.operators.arithmetic;
+
+import net.sf.jsqlparser.expression.BinaryExpression;
+import net.sf.jsqlparser.expression.Expression;
+import net.sf.jsqlparser.expression.ExpressionVisitor;
+
+/** DuckDB's {@code a ** b}, {@code a} raised to the power {@code b}. */
+public class Exponentiation extends BinaryExpression {
+
+ public Exponentiation() {}
+
+ public Exponentiation(Expression leftExpression, Expression rightExpression) {
+ super(leftExpression, rightExpression);
+ }
+
+ @Override
+ public T accept(ExpressionVisitor expressionVisitor, S context) {
+ return expressionVisitor.visit(this, context);
+ }
+
+ @Override
+ public String getStringExpression() {
+ return "**";
+ }
+
+ @Override
+ public Exponentiation withLeftExpression(Expression arg0) {
+ return (Exponentiation) super.withLeftExpression(arg0);
+ }
+
+ @Override
+ public Exponentiation withRightExpression(Expression arg0) {
+ return (Exponentiation) super.withRightExpression(arg0);
+ }
+}
diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/EqualsTo.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/EqualsTo.java
index 8f80f1be88..19f238ffbb 100755
--- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/EqualsTo.java
+++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/EqualsTo.java
@@ -18,6 +18,11 @@ public EqualsTo() {
super("=");
}
+ /** {@code operator} is {@code =} or DuckDB's {@code ==}. */
+ public EqualsTo(String operator) {
+ super(operator);
+ }
+
public EqualsTo(Expression left, Expression right) {
this();
setLeftExpression(left);
diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/FullTextSearch.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/FullTextSearch.java
index 0bf79f0ec8..8c1a8d97ef 100644
--- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/FullTextSearch.java
+++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/FullTextSearch.java
@@ -75,13 +75,13 @@ public T accept(ExpressionVisitor expressionVisitor, S context) {
@Override
public String toString() {
// Build a list of matched columns
- String columnsListCommaSeperated = "";
+ StringBuilder columnsListCommaSeperated = new StringBuilder();
Iterator iterator = this._matchColumns.iterator();
while (iterator.hasNext()) {
Column col = iterator.next();
- columnsListCommaSeperated += col.getFullyQualifiedName();
+ columnsListCommaSeperated.append(col.getFullyQualifiedName());
if (iterator.hasNext()) {
- columnsListCommaSeperated += ",";
+ columnsListCommaSeperated.append(",");
}
}
diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsNormalizedExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsNormalizedExpression.java
new file mode 100644
index 0000000000..bd4593480f
--- /dev/null
+++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsNormalizedExpression.java
@@ -0,0 +1,112 @@
+/*-
+ * #%L
+ * JSQLParser library
+ * %%
+ * Copyright (C) 2004 - 2026 JSQLParser
+ * %%
+ * Dual licensed under GNU LGPL 2.1 or Apache License 2.0
+ * #L%
+ */
+package net.sf.jsqlparser.expression.operators.relational;
+
+import java.util.function.Consumer;
+import net.sf.jsqlparser.expression.Expression;
+import net.sf.jsqlparser.expression.ExpressionVisitor;
+import net.sf.jsqlparser.parser.ASTNodeAccessImpl;
+
+/**
+ * The Unicode normalization test {@code expression IS [NOT] [NFC | NFD | NFKC | NFKD] NORMALIZED}.
+ */
+public class IsNormalizedExpression extends ASTNodeAccessImpl implements Expression {
+ /** The Unicode normalization forms. */
+ public enum NormalForm {
+ NFC, NFD, NFKC, NFKD;
+
+ /** Whether the word names a normalization form, in any case. */
+ public static boolean isNormalForm(String word) {
+ for (NormalForm form : values()) {
+ if (form.name().equalsIgnoreCase(word)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ private Expression leftExpression;
+ private boolean not;
+ private NormalForm normalForm;
+
+ public IsNormalizedExpression() {
+ // empty constructor
+ }
+
+ public IsNormalizedExpression(Expression leftExpression) {
+ this.leftExpression = leftExpression;
+ }
+
+ public Expression getLeftExpression() {
+ return leftExpression;
+ }
+
+ public void setLeftExpression(Expression leftExpression) {
+ this.leftExpression = leftExpression;
+ }
+
+ public IsNormalizedExpression withLeftExpression(Expression leftExpression) {
+ this.setLeftExpression(leftExpression);
+ return this;
+ }
+
+ public E getLeftExpression(Class type) {
+ return type.cast(getLeftExpression());
+ }
+
+ public boolean isNot() {
+ return not;
+ }
+
+ public void setNot(boolean not) {
+ this.not = not;
+ }
+
+ public IsNormalizedExpression withNot(boolean not) {
+ this.setNot(not);
+ return this;
+ }
+
+ /** The normalization form as written, or null when it is omitted (the server tests NFC). */
+ public NormalForm getNormalForm() {
+ return normalForm;
+ }
+
+ public void setNormalForm(NormalForm normalForm) {
+ this.normalForm = normalForm;
+ }
+
+ public IsNormalizedExpression withNormalForm(NormalForm normalForm) {
+ this.setNormalForm(normalForm);
+ return this;
+ }
+
+ @Override
+ public T accept(ExpressionVisitor expressionVisitor, S context) {
+ return expressionVisitor.visit(this, context);
+ }
+
+ /** Appends the test, rendering the operand through the renderer. */
+ public StringBuilder appendTo(StringBuilder builder, Consumer expressionRenderer) {
+ expressionRenderer.accept(leftExpression);
+ builder.append(not ? " IS NOT " : " IS ");
+ if (normalForm != null) {
+ builder.append(normalForm).append(' ');
+ }
+ return builder.append("NORMALIZED");
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ return appendTo(builder, builder::append).toString();
+ }
+}
diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/LikeExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/LikeExpression.java
index 92563d7d85..125e38a825 100644
--- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/LikeExpression.java
+++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/LikeExpression.java
@@ -10,6 +10,7 @@
package net.sf.jsqlparser.expression.operators.relational;
import java.util.Locale;
+import java.util.regex.Pattern;
import net.sf.jsqlparser.expression.BinaryExpression;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.ExpressionVisitor;
@@ -18,6 +19,7 @@ public class LikeExpression extends BinaryExpression implements SupportsOldOracl
private boolean not = false;
private boolean useBinary = false;
private Expression escapeExpression = null;
+ private boolean useOperator = false;
private KeyWord likeKeyWord = KeyWord.LIKE;
public boolean isNot() {
@@ -48,12 +50,64 @@ public String getStringExpression() {
return likeKeyWord.toString();
}
+ /**
+ * The operator spelling of this condition when it was written as one and has one, e.g.
+ * {@code !~~} for {@code NOT LIKE}; otherwise {@code null} and the keyword form is used.
+ */
+ public String getLikeOperator() {
+ if (!useOperator) {
+ return null;
+ }
+ switch (likeKeyWord) {
+ case LIKE:
+ return not ? "!~~" : "~~";
+ case ILIKE:
+ return not ? "!~~*" : "~~*";
+ case GLOB:
+ return not ? null : "~~~";
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Sets the keyword and {@code NOT} from DuckDB's and PostgreSQL's operator spelling: {@code ~~}
+ * is {@code LIKE}, {@code ~~*} {@code ILIKE}, {@code ~~~} {@code GLOB}, and a leading {@code !}
+ * negates the first two. The operator is printed while it matches the keyword and {@code NOT}.
+ */
+ public LikeExpression setLikeOperator(String likeOperator) {
+ if (likeOperator == null) {
+ throw new IllegalArgumentException("The LIKE operator must not be null");
+ }
+ switch (likeOperator) {
+ case "~~":
+ case "!~~":
+ likeKeyWord = KeyWord.LIKE;
+ break;
+ case "~~*":
+ case "!~~*":
+ likeKeyWord = KeyWord.ILIKE;
+ break;
+ case "~~~":
+ likeKeyWord = KeyWord.GLOB;
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown LIKE operator: " + likeOperator);
+ }
+ this.not = likeOperator.startsWith("!");
+ this.useOperator = true;
+ return this;
+ }
+
@Override
public String toString() {
+ String likeOperator = getLikeOperator();
String retval = (oraclePriorPosition == ORACLE_PRIOR_START ? "PRIOR " : "")
- + getLeftExpression() + " " + (not ? "NOT " : "")
- + (likeKeyWord == KeyWord.SIMILAR_TO ? "SIMILAR TO" : likeKeyWord) + " "
- + (useBinary ? "BINARY " : "") + getRightExpression();
+ + getLeftExpression() + " "
+ + (likeOperator != null ? likeOperator
+ : (not ? "NOT " : "")
+ + (likeKeyWord == KeyWord.SIMILAR_TO ? "SIMILAR TO" : likeKeyWord))
+ + " " + (useBinary ? "BINARY " : "") + getRightExpression();
if (escapeExpression != null) {
retval += " ESCAPE " + escapeExpression;
}
@@ -121,9 +175,11 @@ public LikeExpression withRightExpression(Expression arg0) {
public enum KeyWord {
LIKE, ILIKE, RLIKE, REGEXP_LIKE, REGEXP, GLOB, SIMILAR_TO, MATCH_ANY, MATCH_ALL, MATCH_PHRASE, MATCH_PHRASE_PREFIX, MATCH_REGEXP;
+ private static final Pattern WHITESPACE = Pattern.compile("\\s+");
+
public static KeyWord from(String keyword) {
return Enum.valueOf(KeyWord.class,
- keyword.toUpperCase(Locale.ROOT).replaceAll("\\s+", "_"));
+ WHITESPACE.matcher(keyword.toUpperCase(Locale.ROOT)).replaceAll("_"));
}
}
diff --git a/src/main/java/net/sf/jsqlparser/parser/ASTNodeAccessImpl.java b/src/main/java/net/sf/jsqlparser/parser/ASTNodeAccessImpl.java
index 6ef61996b6..3a1ad53294 100644
--- a/src/main/java/net/sf/jsqlparser/parser/ASTNodeAccessImpl.java
+++ b/src/main/java/net/sf/jsqlparser/parser/ASTNodeAccessImpl.java
@@ -9,6 +9,9 @@
*/
package net.sf.jsqlparser.parser;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
import java.util.Set;
import java.util.TreeSet;
@@ -26,6 +29,26 @@ public void setASTNode(Node node) {
this.node = node;
}
+ /**
+ * The comments preceding this node's first token, in source order, with the original token
+ * images. Line comments do not include their line terminator; callers must add a line break
+ * when prepending them to SQL. Empty for nodes built programmatically, which carry no AST.
+ */
+ public List getLeadingComments() {
+ Node node = getASTNode();
+ if (node == null) {
+ return new ArrayList<>();
+ }
+ List comments = new ArrayList<>();
+ for (Token specialToken =
+ node.jjtGetFirstToken().specialToken; specialToken != null; specialToken =
+ specialToken.specialToken) {
+ comments.add(specialToken.image);
+ }
+ Collections.reverse(comments);
+ return comments;
+ }
+
public StringBuilder appendTo(StringBuilder builder) {
// don't add spaces around the following punctuation
final Set punctuation = new TreeSet<>(Set.of(".", "[", "]"));
@@ -48,22 +71,20 @@ public StringBuilder appendTo(StringBuilder builder) {
return builder;
}
+ /**
+ * The nearest enclosing object in the tree, or null when there is none. A node that carries
+ * only a token range, for an object no grammar rule opens a tree node for, has no parent.
+ */
public ASTNodeAccess getParent() {
- Node parent = (Node) node.jjtGetParent();
- while (parent.jjtGetValue() == null) {
- parent = (Node) parent.jjtGetParent();
- }
-
- return ASTNodeAccess.class.cast(parent.jjtGetValue());
+ return getParent(ASTNodeAccess.class);
}
public T getParent(Class clazz) {
- Node parent = (Node) node.jjtGetParent();
- while (parent.jjtGetValue() == null || !clazz.isInstance(parent.jjtGetValue())) {
+ Node parent = node == null ? null : (Node) node.jjtGetParent();
+ while (parent != null && !clazz.isInstance(parent.jjtGetValue())) {
parent = (Node) parent.jjtGetParent();
}
-
- return clazz.cast(parent.jjtGetValue());
+ return parent == null ? null : clazz.cast(parent.jjtGetValue());
}
@Override
diff --git a/src/main/java/net/sf/jsqlparser/parser/AbstractJSqlParser.java b/src/main/java/net/sf/jsqlparser/parser/AbstractJSqlParser.java
index a394558459..28d969ed16 100644
--- a/src/main/java/net/sf/jsqlparser/parser/AbstractJSqlParser.java
+++ b/src/main/java/net/sf/jsqlparser/parser/AbstractJSqlParser.java
@@ -11,6 +11,8 @@
import net.sf.jsqlparser.parser.feature.Feature;
import net.sf.jsqlparser.parser.feature.FeatureConfiguration;
+import net.sf.jsqlparser.statement.update.UpdateConflictAlgorithm;
+import net.sf.jsqlparser.statement.upsert.UpsertType;
import java.util.ArrayList;
import java.util.Collections;
@@ -39,7 +41,8 @@ public enum Dialect {
Feature.allowDoubleQuotedStrings), SQLSERVER(AdjacentStringLiterals.OFF,
Feature.allowSquareBracketQuotation), POSTGRESQL(
AdjacentStringLiterals.NEWLINE,
- Feature.allowDollarQuotedStringTags), H2, EXASOL, BIGQUERY(
+ Feature.allowDollarQuotedStringTags,
+ Feature.allowDigitSeparators), H2, EXASOL, BIGQUERY(
AdjacentStringLiterals.WHITESPACE,
Feature.allowDoubleQuotedStrings,
Feature.allowHashLineComments,
@@ -47,7 +50,7 @@ public enum Dialect {
AdjacentStringLiterals.WHITESPACE,
Feature.allowDoubleQuotedStrings,
Feature.allowBackslashEscapeCharacter), SNOWFLAKE(
- Feature.allowBackslashEscapeCharacter), INFORMIX, SPANNER, DORIS, COCKROACHDB, TERADATA;
+ Feature.allowBackslashEscapeCharacter), INFORMIX, SPANNER, DORIS, COCKROACHDB, TERADATA, SQLITE;
private final Set lexerFeatures;
private final AdjacentStringLiterals adjacentStringLiterals;
@@ -109,6 +112,21 @@ public P withLegacyMySqlGroupBy(boolean enabled) {
return withFeature(Feature.allowLegacyMySqlGroupBy, enabled);
}
+ /**
+ * Resolves MySQL executable comments against this server version (for example 90702 for 9.7.2).
+ * Requires the MYSQL dialect. Rendered SQL reflects this version, without conditional wrappers.
+ * Without an explicit version, conditional executable comments raise a lexical error.
+ *
+ * @param version major * 10000 + minor * 100 + patch, from 0 through 999999
+ * @return this parser
+ */
+ public P withMySqlServerVersion(int version) {
+ if (version < 0 || version > 999999) {
+ throw new IllegalArgumentException("MySQL server version must be between 0 and 999999");
+ }
+ return withFeature(Feature.mySqlServerVersion, (long) version);
+ }
+
public P withTimeOut(long timeOutMillSeconds) {
return withFeature(Feature.timeOut, timeOutMillSeconds);
}
@@ -179,6 +197,19 @@ public P withHashLineComments(boolean allowHashLineComments) {
return withFeature(Feature.allowHashLineComments, allowHashLineComments);
}
+ public P withBlankLinesAsSeparator(boolean allowBlankLinesAsStatementSeparator) {
+ return withFeature(Feature.allowBlankLinesAsStatementSeparator,
+ allowBlankLinesAsStatementSeparator);
+ }
+
+ public P withDigitSeparators() {
+ return withFeature(Feature.allowDigitSeparators, true);
+ }
+
+ public P withDigitSeparators(boolean allowDigitSeparators) {
+ return withFeature(Feature.allowDigitSeparators, allowDigitSeparators);
+ }
+
public P withUnparenthesizedSubSelects() {
return withFeature(Feature.allowUnparenthesizedSubSelects, true);
}
@@ -230,6 +261,42 @@ public Integer getAsInteger(Feature f) {
return getConfiguration().getAsInteger(f);
}
+ /**
+ * The INSERT OR conflict algorithms other than REPLACE are SQLite syntax.
+ */
+ protected UpsertType insertOrType(String algorithm) throws ParseException {
+ if ("REPLACE".equalsIgnoreCase(algorithm)) {
+ return UpsertType.INSERT_OR_REPLACE;
+ }
+ if (!Dialect.SQLITE.name().equals(getAsString(Feature.dialect))) {
+ throw new ParseException("INSERT OR " + algorithm + " needs Dialect.SQLITE");
+ }
+ switch (algorithm.toUpperCase()) {
+ case "IGNORE":
+ return UpsertType.INSERT_OR_IGNORE;
+ case "ROLLBACK":
+ return UpsertType.INSERT_OR_ROLLBACK;
+ case "ABORT":
+ return UpsertType.INSERT_OR_ABORT;
+ case "FAIL":
+ return UpsertType.INSERT_OR_FAIL;
+ default:
+ throw new ParseException("Expected ABORT, FAIL, IGNORE, REPLACE or ROLLBACK");
+ }
+ }
+
+ protected UpdateConflictAlgorithm updateOrAlgorithm(String algorithm) throws ParseException {
+ if (!Dialect.SQLITE.name().equals(getAsString(Feature.dialect))) {
+ throw new ParseException("UPDATE OR " + algorithm + " needs Dialect.SQLITE");
+ }
+ for (UpdateConflictAlgorithm conflictAlgorithm : UpdateConflictAlgorithm.values()) {
+ if (conflictAlgorithm.name().equalsIgnoreCase(algorithm)) {
+ return conflictAlgorithm;
+ }
+ }
+ throw new ParseException("Expected ABORT, FAIL, IGNORE, REPLACE or ROLLBACK");
+ }
+
public String getAsString(Feature f) {
return getConfiguration().getAsString(f);
}
diff --git a/src/main/java/net/sf/jsqlparser/parser/CCJSqlParserUtil.java b/src/main/java/net/sf/jsqlparser/parser/CCJSqlParserUtil.java
index f187b7da1f..f3bbdc7ac0 100644
--- a/src/main/java/net/sf/jsqlparser/parser/CCJSqlParserUtil.java
+++ b/src/main/java/net/sf/jsqlparser/parser/CCJSqlParserUtil.java
@@ -278,50 +278,37 @@ private static ColDataType parseColDataType(String columnDataType, boolean allow
}
}
- @SuppressWarnings("PMD.CyclomaticComplexity")
public static Expression parseExpression(String expressionStr, boolean allowPartialParse,
Consumer consumer) throws JSQLParserException {
if (expressionStr == null || expressionStr.isEmpty()) {
return null;
}
- Expression expression = null;
- // first, try to parse fast and simple
+ // First require a complete simple parse, even when the caller allows a partial result.
try {
- CCJSqlParser parser = newParser(expressionStr).withAllowComplexParsing(false);
- if (consumer != null) {
- consumer.accept(parser);
- }
- try {
- expression = parser.Expression();
- if (parser.getNextToken().kind != CCJSqlParserTokenManager.EOF) {
- throw new JSQLParserException(
- "could only parse partial expression " + expression.toString());
- }
- } catch (ParseException ex) {
- throw new JSQLParserException(expressionStr, ex);
- }
- } catch (JSQLParserException ex1) {
- // when fast simple parsing fails, try complex parsing but only if it has a chance to
- // succeed
- CCJSqlParser parser = newParser(expressionStr).withAllowComplexParsing(true);
- if (consumer != null) {
- consumer.accept(parser);
- }
- try {
- expression = parser.Expression();
- if (!allowPartialParse
- && parser.getNextToken().kind != CCJSqlParserTokenManager.EOF) {
- throw new JSQLParserException(
- "could only parse partial expression " + expression.toString());
- }
- } catch (JSQLParserException ex) {
- throw ex;
- } catch (ParseException ex) {
- throw new JSQLParserException(ex);
+ return parseExpression(expressionStr, false, false, consumer);
+ } catch (JSQLParserException ex) {
+ return parseExpression(expressionStr, true, allowPartialParse, consumer);
+ }
+ }
+
+ private static Expression parseExpression(String expressionStr, boolean allowComplexParsing,
+ boolean allowPartialParse, Consumer consumer) throws JSQLParserException {
+ CCJSqlParser parser = newParser(expressionStr).withAllowComplexParsing(allowComplexParsing);
+ if (consumer != null) {
+ consumer.accept(parser);
+ }
+
+ try {
+ Expression expression = parser.Expression();
+ if (!allowPartialParse && parser.getNextToken().kind != CCJSqlParserTokenManager.EOF) {
+ throw new JSQLParserException(
+ "could only parse partial expression " + expression.toString());
}
+ return expression;
+ } catch (ParseException ex) {
+ throw new JSQLParserException(ex);
}
- return expression;
}
/**
@@ -356,50 +343,9 @@ public static Expression parseCondExpression(String condExpr, boolean allowParti
});
}
- @SuppressWarnings("PMD.CyclomaticComplexity")
public static Expression parseCondExpression(String conditionalExpressionStr,
boolean allowPartialParse, Consumer consumer) throws JSQLParserException {
- if (conditionalExpressionStr == null || conditionalExpressionStr.isEmpty()) {
- return null;
- }
-
- Expression expression = null;
- // first, try to parse fast and simple
- try {
- CCJSqlParser parser =
- newParser(conditionalExpressionStr).withAllowComplexParsing(false);
- if (consumer != null) {
- consumer.accept(parser);
- }
- try {
- expression = parser.Expression();
- if (parser.getNextToken().kind != CCJSqlParserTokenManager.EOF) {
- throw new JSQLParserException(
- "could only parse partial expression " + expression.toString());
- }
- } catch (ParseException ex) {
- throw new JSQLParserException(ex);
- }
- } catch (JSQLParserException ex1) {
- CCJSqlParser parser =
- newParser(conditionalExpressionStr).withAllowComplexParsing(true);
- if (consumer != null) {
- consumer.accept(parser);
- }
- try {
- expression = parser.Expression();
- if (!allowPartialParse
- && parser.getNextToken().kind != CCJSqlParserTokenManager.EOF) {
- throw new JSQLParserException(
- "could only parse partial expression " + expression.toString());
- }
- } catch (JSQLParserException ex) {
- throw ex;
- } catch (ParseException ex) {
- throw new JSQLParserException(ex);
- }
- }
- return expression;
+ return parseExpression(conditionalExpressionStr, allowPartialParse, consumer);
}
/**
diff --git a/src/main/java/net/sf/jsqlparser/parser/RangeNode.java b/src/main/java/net/sf/jsqlparser/parser/RangeNode.java
new file mode 100644
index 0000000000..9b025a2ebc
--- /dev/null
+++ b/src/main/java/net/sf/jsqlparser/parser/RangeNode.java
@@ -0,0 +1,71 @@
+/*-
+ * #%L
+ * JSQLParser library
+ * %%
+ * Copyright (C) 2004 - 2026 JSQLParser
+ * %%
+ * Dual licensed under GNU LGPL 2.1 or Apache License 2.0
+ * #L%
+ */
+package net.sf.jsqlparser.parser;
+
+/**
+ * A node outside the parse tree that records the tokens an object spans. It serves an object no
+ * grammar rule opens a tree node for, or one whose text runs past its tree node. In that second
+ * case it stands in for the tree node, answering its parent, children and id, with the wider range.
+ */
+final class RangeNode extends Node {
+ private final Node treeNode;
+
+ RangeNode(Token first, Token last, Node treeNode) {
+ super(CCJSqlParserTreeConstants.JJTEXPRESSION);
+ this.treeNode = treeNode;
+ jjtSetFirstToken(first);
+ jjtSetLastToken(last);
+ }
+
+ @Override
+ public Node jjtGetParent() {
+ return treeNode == null ? null : treeNode.jjtGetParent();
+ }
+
+ @Override
+ public Node[] jjtGetChildren() {
+ return treeNode == null ? super.jjtGetChildren() : treeNode.jjtGetChildren();
+ }
+
+ @Override
+ public Node jjtGetChild(int i) {
+ return treeNode == null ? super.jjtGetChild(i) : treeNode.jjtGetChild(i);
+ }
+
+ @Override
+ public int jjtGetNumChildren() {
+ return treeNode == null ? super.jjtGetNumChildren() : treeNode.jjtGetNumChildren();
+ }
+
+ @Override
+ public Object childrenAccept(CCJSqlParserVisitor visitor, Object data) {
+ return treeNode == null ? super.childrenAccept(visitor, data)
+ : treeNode.childrenAccept(visitor, data);
+ }
+
+ @Override
+ public int getId() {
+ return treeNode == null ? super.getId() : treeNode.getId();
+ }
+
+ @Override
+ public String toString() {
+ return treeNode == null ? super.toString() : treeNode.toString();
+ }
+
+ @Override
+ public void dump(String prefix) {
+ if (treeNode == null) {
+ super.dump(prefix);
+ } else {
+ treeNode.dump(prefix);
+ }
+ }
+}
diff --git a/src/main/java/net/sf/jsqlparser/parser/RoutineBodyBoundary.java b/src/main/java/net/sf/jsqlparser/parser/RoutineBodyBoundary.java
new file mode 100644
index 0000000000..02b1c0b9c5
--- /dev/null
+++ b/src/main/java/net/sf/jsqlparser/parser/RoutineBodyBoundary.java
@@ -0,0 +1,295 @@
+/*-
+ * #%L
+ * JSQLParser library
+ * %%
+ * Copyright (C) 2004 - 2026 JSQLParser
+ * %%
+ * Dual licensed under GNU LGPL 2.1 or Apache License 2.0
+ * #L%
+ */
+package net.sf.jsqlparser.parser;
+
+import static net.sf.jsqlparser.parser.CCJSqlParserConstants.*;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+/**
+ * Finds the boundary of an opaque routine without interpreting its statements. In particular,
+ * expression CASE and procedural END qualifiers must not close an enclosing BEGIN block.
+ */
+final class RoutineBodyBoundary {
+ private enum Block {
+ BEGIN, IF, CASE_STATEMENT, CASE_EXPRESSION, LOOP, WHILE, REPEAT
+ }
+
+ private final Deque blocks = new ArrayDeque<>();
+ private int parentheses;
+ private int previousKind = -1;
+ private int statementKind = -1;
+ private boolean hasParameters;
+ private boolean standardReturns;
+ private boolean returnTypeName;
+ private boolean afterDot;
+ private boolean declarations;
+ private boolean bodyStarted;
+ private boolean compoundBody;
+ private boolean quotedBody;
+ private boolean completed;
+ private boolean handlerAction;
+ private boolean statementStart = true;
+
+ /**
+ * Tracks a compound statement without a routine header, such as a MySQL trigger body. Its
+ * tokens belong to the body from the start, as after a routine's parameter list.
+ */
+ static RoutineBodyBoundary forCompoundStatement() {
+ RoutineBodyBoundary boundary = new RoutineBodyBoundary();
+ boundary.hasParameters = true;
+ return boundary;
+ }
+
+ boolean endsAt(Token token) throws ParseException {
+ if (token.kind == EOF) {
+ if (!blocks.isEmpty()) {
+ throw new ParseException("Unterminated routine block");
+ }
+ return true;
+ }
+ return token.kind == ST_SEMICOLON && parentheses == 0 && blocks.isEmpty()
+ && !declarations && (hasParameters || quotedBody || completed);
+ }
+
+ /**
+ * Whether the routine header, including a return type, is complete and the body has not
+ * started, which is where MySQL routine characteristics appear.
+ */
+ boolean isBeforeBody() {
+ return hasParameters && parentheses == 0 && !bodyStarted && !returnTypeName
+ && !declarations && !quotedBody && !completed;
+ }
+
+ boolean startsQuotedBody(Token token, Token next) {
+ return parentheses == 0 && !compoundBody && !quotedBody && token.kind == K_AS
+ && next.kind == S_CHAR_LITERAL
+ && (!bodyStarted || statementKind == K_RETURN || statementKind == K_SET);
+ }
+
+ void quotedBody() {
+ quotedBody = true;
+ bodyStarted = true;
+ declarations = false;
+ }
+
+ void accept(Token token, Token next) {
+ int kind = token.kind;
+ if (kind == OPENING_BRACKET) {
+ parentheses++;
+ } else if (kind == CLOSING_BRACKET) {
+ if (--parentheses == 0 && !bodyStarted) {
+ hasParameters = true;
+ }
+ } else if (parentheses == 0 && !quotedBody && !completed) {
+ acceptTopLevel(token, next);
+ }
+ previousKind = kind;
+ afterDot = ".".equals(token.image);
+ }
+
+ private void acceptTopLevel(Token token, Token next) {
+ if (afterDot) {
+ return; // Qualified type/column names may use otherwise significant keywords.
+ }
+ // END IF/CASE/LOOP/WHILE/REPEAT is one terminator, not another opener.
+ if (previousKind == K_END && isEndQualifier(token)) {
+ return;
+ }
+ if (!acceptRoutineHeader(token)) {
+ acceptBodyToken(token, next);
+ }
+ }
+
+ private boolean acceptRoutineHeader(Token token) {
+ int kind = token.kind;
+ if (kind == K_RETURNS && !bodyStarted) {
+ standardReturns = true;
+ returnTypeName = true;
+ return true;
+ }
+ if (returnTypeName) {
+ returnTypeName = keyword(token, "SETOF");
+ return true;
+ }
+ if (!compoundBody && (kind == K_AS || kind == K_IS)
+ && (!bodyStarted || statementKind == K_RETURN && !standardReturns
+ || statementKind == K_SET)) {
+ declarations = true;
+ bodyStarted = false;
+ return true;
+ }
+ return false;
+ }
+
+ private void acceptBodyToken(Token token, Token next) {
+ int kind = token.kind;
+ if (acceptStatementBoundary(kind)) {
+ return;
+ }
+ if (!(hasParameters || declarations || bodyStarted)) {
+ return;
+ }
+ if (handlerAction && isSimpleStatementStart(kind)) {
+ startStatement();
+ }
+ if (acceptBeginOrCase(kind) || declarations || acceptControlFlow(token)) {
+ return;
+ }
+ acceptStatementToken(token, next);
+ }
+
+ private boolean acceptStatementBoundary(int kind) {
+ if (kind == ST_SEMICOLON) {
+ startStatement();
+ return true;
+ }
+ if (kind == K_END) {
+ if (!blocks.isEmpty()) {
+ Block closed = blocks.pop();
+ completed = blocks.isEmpty() && closed != Block.CASE_EXPRESSION;
+ } else {
+ // Retain legacy opaque declarations without a parameter list or BEGIN.
+ completed = true;
+ }
+ statementStart = false;
+ return true;
+ }
+ return false;
+ }
+
+ private boolean acceptBeginOrCase(int kind) {
+ if (kind == K_BEGIN
+ && (!bodyStarted || statementStart || statementKind == K_DECLARE)) {
+ blocks.push(Block.BEGIN);
+ declarations = false;
+ compoundBody = true;
+ bodyStarted = true;
+ startStatement();
+ return true;
+ }
+ if (kind == K_CASE) {
+ boolean statementCase = !declarations && (statementStart || handlerAction);
+ blocks.push(statementCase ? Block.CASE_STATEMENT : Block.CASE_EXPRESSION);
+ if (statementCase) {
+ bodyStarted = true;
+ compoundBody = true;
+ handlerAction = false;
+ }
+ statementStart = false;
+ return true;
+ }
+ return false;
+ }
+
+ private boolean acceptControlFlow(Token token) {
+ int kind = token.kind;
+ Block block = controlBlock(token);
+ if ((statementStart || handlerAction) && block != null) {
+ blocks.push(block);
+ bodyStarted = true;
+ compoundBody = true;
+ handlerAction = false;
+ statementKind = kind;
+ statementStart = block == Block.LOOP || block == Block.REPEAT;
+ return true;
+ }
+ if (acceptOracleLoop(kind)) {
+ return true;
+ }
+ if (isStatementBranch(kind)) {
+ startStatement();
+ return true;
+ }
+ return false;
+ }
+
+ private boolean acceptOracleLoop(int kind) {
+ if (kind == K_LOOP && (statementKind == K_FOR || blocks.peek() == Block.WHILE)) {
+ // Oracle FOR/WHILE ... LOOP shares the same END LOOP boundary.
+ if (blocks.peek() != Block.WHILE) {
+ blocks.push(Block.LOOP);
+ }
+ startStatement();
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isStatementBranch(int kind) {
+ return (kind == K_THEN || kind == K_ELSE) && !blocks.isEmpty()
+ && blocks.peek() != Block.CASE_EXPRESSION
+ || kind == K_DO && blocks.peek() == Block.WHILE;
+ }
+
+ private void acceptStatementToken(Token token, Token next) {
+ int kind = token.kind;
+ if (isStatementPrefix(token, next)) {
+ return;
+ }
+ if (!bodyStarted) {
+ // SET may also be a PostgreSQL header option; AS remains recognizable above.
+ // CHARACTER SET and CHAR SET belong to a MySQL return type.
+ boolean characterSet =
+ kind == K_SET && (previousKind == K_CHARACTER || previousKind == K_CHAR);
+ if (!isSimpleStatementStart(kind) || characterSet) {
+ return;
+ }
+ bodyStarted = true;
+ }
+ if (statementStart) {
+ statementKind = kind;
+ }
+ if (statementKind == K_DECLARE && token.kind == K_HANDLER) {
+ handlerAction = true;
+ }
+ statementStart = false;
+ }
+
+ private boolean isStatementPrefix(Token token, Token next) {
+ // ATOMIC and a label precede the statement they qualify.
+ return previousKind == K_BEGIN && keyword(token, "ATOMIC")
+ || statementStart && (":".equals(next.image) || ":".equals(token.image));
+ }
+
+ private static boolean isEndQualifier(Token token) {
+ return token.kind == K_CASE || controlBlock(token) != null;
+ }
+
+ private static Block controlBlock(Token token) {
+ if (token.kind == K_IF) {
+ return Block.IF;
+ }
+ if (token.kind == K_LOOP) {
+ return Block.LOOP;
+ }
+ if (keyword(token, "WHILE")) {
+ return Block.WHILE;
+ }
+ return keyword(token, "REPEAT") ? Block.REPEAT : null;
+ }
+
+ private void startStatement() {
+ statementStart = true;
+ statementKind = -1;
+ handlerAction = false;
+ }
+
+ private static boolean keyword(Token token, String keyword) {
+ return token.kind == S_IDENTIFIER && keyword.equalsIgnoreCase(token.image);
+ }
+
+ private static boolean isSimpleStatementStart(int kind) {
+ return kind == K_RETURN || kind == K_SELECT || kind == K_INSERT || kind == K_UPDATE
+ || kind == K_DELETE || kind == K_REPLACE || kind == K_SET || kind == K_CALL
+ || kind == K_WITH || kind == K_DO;
+ }
+}
diff --git a/src/main/java/net/sf/jsqlparser/parser/SimpleCharStream.java b/src/main/java/net/sf/jsqlparser/parser/SimpleCharStream.java
index ca81a8dd11..5b6c5e8259 100644
--- a/src/main/java/net/sf/jsqlparser/parser/SimpleCharStream.java
+++ b/src/main/java/net/sf/jsqlparser/parser/SimpleCharStream.java
@@ -10,9 +10,10 @@
/* Generated By:JavaCC: Do not edit this line by hand. SimpleCharStream.java Version 8.0.0 */
/*
* Warning: this file is maintained by hand on top of the JavaCC template. Among other manual
- * adjustments it carries the in-buffer '#' rewrite in BeginToken(), which
- * Feature.allowHashLineComments depends on. Never overwrite it with a freshly generated
- * SimpleCharStream, that would silently drop the rewrite and break allowHashLineComments.
+ * adjustments it carries the in-buffer '#' and blank line rewrites in BeginToken(), which
+ * Feature.allowHashLineComments and Feature.allowBlankLinesAsStatementSeparator depend on. Never
+ * overwrite it with a freshly generated SimpleCharStream, that would silently drop the rewrites and
+ * break both features.
*/
package net.sf.jsqlparser.parser;
@@ -47,6 +48,9 @@ public class SimpleCharStream {
protected boolean trackLineColumn = true;
protected int totalCharsRead = 0;
protected int absoluteTokenBegin = 0;
+ // line, column and absolute position of each match begun since the last positionSpecialTokens()
+ private int[] matchBegins = new int[24];
+ private int matchBeginCount = 0;
int bufsize;
int available;
int tokenBegin;
@@ -60,7 +64,12 @@ public class SimpleCharStream {
// the `#` in the token image. Wired (with the token manager's
// configuration) before parsing, null keeps this inert.
static final char HASH_SUBSTITUTION = '\u0001';
+ static final char MYSQL_MINUS_SUBSTITUTION = '\u0002';
+ static final char MYSQL_COMMENT_ERROR = '\u0003';
FeatureConfiguration featureConfiguration;
+ private boolean mySqlExecutableComment;
+ String mySqlCommentError;
+ boolean mySqlMinusSubstitution;
/**
* Constructor.
@@ -101,6 +110,38 @@ public final int getAbsoluteTokenBegin() {
return absoluteTokenBegin;
}
+ /**
+ * Gives the comments in front of {@code token} the positions where their matches began, from
+ * the begins recorded since the last call, and forgets those. Comments come through no token
+ * action, so this is how they get a position. The comments chain backwards from the token while
+ * the begins are recorded forwards, so one backwards pass pairs them.
+ */
+ public final void positionSpecialTokens(Token token) {
+ int i = matchBeginCount - 3;
+ for (Token comment = token.specialToken; comment != null; comment = comment.specialToken) {
+ while (i >= 0 && (matchBegins[i] != comment.beginLine
+ || matchBegins[i + 1] != comment.beginColumn)) {
+ i -= 3;
+ }
+ if (i < 0) {
+ break;
+ }
+ comment.absoluteBegin = matchBegins[i + 2];
+ comment.absoluteEnd = comment.absoluteBegin + comment.image.length();
+ i -= 3;
+ }
+ matchBeginCount = 0;
+ }
+
+ private void recordMatchBegin() {
+ if (matchBeginCount + 3 > matchBegins.length) {
+ matchBegins = java.util.Arrays.copyOf(matchBegins, matchBegins.length * 2);
+ }
+ matchBegins[matchBeginCount++] = getBeginLine();
+ matchBegins[matchBeginCount++] = getBeginColumn();
+ matchBegins[matchBeginCount++] = absoluteTokenBegin;
+ }
+
protected void ExpandBuff(boolean wrapAround) {
final int newSize = bufsize * 2;
char[] newbuffer = new char[newSize];
@@ -173,20 +214,138 @@ protected void FillBuff() throws java.io.IOException {
* Start.
*/
public final char BeginToken() throws java.io.IOException {
+ mySqlMinusSubstitution = false;
+ if (mySqlCommentError != null) {
+ // Parser lookahead may catch lexical errors. Keep this failure sticky until ReInit
+ // rather than allowing a later token request to continue after the rejected marker.
+ return MYSQL_COMMENT_ERROR;
+ }
tokenBegin = -1;
- char c = readChar();
+ char c;
+ try {
+ c = readChar();
+ } catch (java.io.IOException e) {
+ if (!mySqlExecutableComment) {
+ throw e;
+ }
+ // JavaCC treats exceptions from BeginToken as EOF. Emit a real token whose lexical
+ // action reports the error, so an unclosed executable comment cannot succeed as SQL.
+ c = mySqlCommentError("Unterminated MySQL executable comment");
+ }
tokenBegin = bufpos;
absoluteTokenBegin = totalCharsRead;
+ recordMatchBegin();
if (c == '#' && featureConfiguration != null
&& featureConfiguration.getAsBoolean(Feature.allowHashLineComments)) {
buffer[bufpos] = HASH_SUBSTITUTION;
c = HASH_SUBSTITUTION;
+ } else if ((c == '-' || c == '/' || c == '*') && featureConfiguration != null
+ && AbstractJSqlParser.Dialect.MYSQL.name()
+ .equals(featureConfiguration.getValue(Feature.dialect))) {
+ c = mySqlCommentBoundary(c);
+ } else if (c == '\n' && featureConfiguration != null
+ && !featureConfiguration
+ .getAsBoolean(Feature.allowBlankLinesAsStatementSeparator)
+ && peekCharacters(2).equals("\n\n")) {
+ // Blanking the first newline of the run stops ST_SEMICOLON matching "\n\n\n";
+ // line and column tracking was already updated when the newline was read.
+ buffer[bufpos] = ' ';
+ c = ' ';
}
return c;
}
+ /** Changes only token boundaries, never characters being scanned inside strings or names. */
+ private char mySqlCommentBoundary(char c) throws java.io.IOException {
+ if (c == '-') {
+ String following = peekCharacters(2);
+ if (following.length() == 2 && following.charAt(0) == '-'
+ && !isMySqlCommentSpace(following.charAt(1))) {
+ mySqlMinusSubstitution = true;
+ buffer[bufpos] = MYSQL_MINUS_SUBSTITUTION;
+ return MYSQL_MINUS_SUBSTITUTION;
+ }
+ } else if (c == '*' && mySqlExecutableComment && peekCharacters(1).equals("/")) {
+ eraseCommentMarker(2);
+ mySqlExecutableComment = false;
+ return ' ';
+ } else if (c == '/') {
+ String following = peekCharacters(9);
+ if (following.startsWith("*!")) {
+ if (mySqlExecutableComment) {
+ return mySqlCommentError("Nested MySQL executable comments are not supported");
+ }
+ int digits = mySqlCommentVersionLength(following);
+ if (digits > 0) {
+ long target = featureConfiguration.getAsLong(Feature.mySqlServerVersion);
+ if (target < 0 || target > 999999) {
+ return mySqlCommentError("MySQL conditional executable comments require "
+ + "withMySqlServerVersion(major * 10000 + minor * 100 + patch)");
+ }
+ int minimum = Integer.parseInt(following.substring(2, 2 + digits));
+ if (minimum > target) {
+ return c;
+ }
+ }
+ eraseCommentMarker(3 + digits);
+ mySqlExecutableComment = true;
+ return ' ';
+ }
+ }
+ return c;
+ }
+
+ private static boolean isMySqlCommentSpace(char c) {
+ return c <= ' ' || c == '\u007f';
+ }
+
+ private static int mySqlCommentVersionLength(String following) {
+ if (following.length() < 7) {
+ return 0;
+ }
+ for (int i = 2; i < 7; i++) {
+ if (following.charAt(i) < '0' || following.charAt(i) > '9') {
+ return 0;
+ }
+ }
+ // MySQL recognizes a sixth digit only when followed by whitespace. Otherwise the
+ // five-digit prefix is the version and the remaining characters belong to the SQL body.
+ return following.length() >= 9 && following.charAt(7) >= '0'
+ && following.charAt(7) <= '9' && (following.charAt(8) == ' '
+ || following.charAt(8) >= '\t' && following.charAt(8) <= '\r')
+ ? 6
+ : 5;
+ }
+
+ private String peekCharacters(int length) {
+ StringBuilder result = new StringBuilder(length);
+ try {
+ for (int i = 0; i < length; i++) {
+ result.append(readChar());
+ }
+ } catch (java.io.IOException ignored) {
+ // Only the successfully read characters need to be rewound, including at EOF.
+ }
+ backup(result.length());
+ return result.toString();
+ }
+
+ private void eraseCommentMarker(int length) throws java.io.IOException {
+ buffer[bufpos] = ' ';
+ for (int i = 1; i < length; i++) {
+ readChar();
+ buffer[bufpos] = ' ';
+ }
+ backup(length - 1);
+ }
+
+ private char mySqlCommentError(String message) {
+ mySqlCommentError = message;
+ return MYSQL_COMMENT_ERROR;
+ }
+
protected final void UpdateLineColumn(char c) {
column++;
@@ -318,6 +477,7 @@ public final void backup(int amount) {
* Reinitialise.
*/
public void ReInit(Provider dstream, int startline, int startcolumn, int buffersize) {
+ matchBeginCount = 0;
inputStream = dstream;
line = startline;
column = startcolumn - 1;
@@ -330,6 +490,8 @@ public void ReInit(Provider dstream, int startline, int startcolumn, int buffers
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
bufpos = -1;
+ mySqlExecutableComment = false;
+ mySqlCommentError = null;
}
/**
@@ -362,6 +524,8 @@ public String GetImage() {
String image = doGetImage();
if (!image.isEmpty() && image.charAt(0) == HASH_SUBSTITUTION) {
image = "#" + image.substring(1);
+ } else if (!image.isEmpty() && image.charAt(0) == MYSQL_MINUS_SUBSTITUTION) {
+ image = "-" + image.substring(1);
}
return image;
}
diff --git a/src/main/java/net/sf/jsqlparser/parser/feature/Feature.java b/src/main/java/net/sf/jsqlparser/parser/feature/Feature.java
index e09ae85535..60f8850dc7 100644
--- a/src/main/java/net/sf/jsqlparser/parser/feature/Feature.java
+++ b/src/main/java/net/sf/jsqlparser/parser/feature/Feature.java
@@ -22,14 +22,26 @@
import net.sf.jsqlparser.statement.DeclareStatement;
import net.sf.jsqlparser.statement.DescribeStatement;
import net.sf.jsqlparser.statement.ExplainStatement;
+import net.sf.jsqlparser.statement.PluginStatement;
+import net.sf.jsqlparser.statement.PrepareTransactionStatement;
import net.sf.jsqlparser.statement.ResetStatement;
+import net.sf.jsqlparser.statement.SetConstraintsStatement;
import net.sf.jsqlparser.statement.SetStatement;
+import net.sf.jsqlparser.statement.SetTransactionStatement;
import net.sf.jsqlparser.statement.ShowColumnsStatement;
import net.sf.jsqlparser.statement.ShowStatement;
+import net.sf.jsqlparser.statement.TableMaintenanceStatement;
import net.sf.jsqlparser.statement.UseStatement;
+import net.sf.jsqlparser.statement.XaStatement;
+import net.sf.jsqlparser.statement.admin.FlushStatement;
+import net.sf.jsqlparser.statement.admin.KillStatement;
import net.sf.jsqlparser.statement.alter.Alter;
+import net.sf.jsqlparser.statement.alter.AlterEventTrigger;
import net.sf.jsqlparser.statement.alter.sequence.AlterSequence;
import net.sf.jsqlparser.statement.analyze.Analyze;
+import net.sf.jsqlparser.statement.maintenance.CheckpointStatement;
+import net.sf.jsqlparser.statement.maintenance.ClusterStatement;
+import net.sf.jsqlparser.statement.maintenance.VacuumStatement;
import net.sf.jsqlparser.statement.comment.Comment;
import net.sf.jsqlparser.statement.create.database.CreateDatabase;
import net.sf.jsqlparser.statement.create.function.CreateFunction;
@@ -39,14 +51,26 @@
import net.sf.jsqlparser.statement.create.sequence.CreateSequence;
import net.sf.jsqlparser.statement.create.synonym.CreateSynonym;
import net.sf.jsqlparser.statement.create.table.CreateTable;
+import net.sf.jsqlparser.statement.create.trigger.CreateEventTrigger;
import net.sf.jsqlparser.statement.create.view.AlterView;
import net.sf.jsqlparser.statement.create.view.CreateView;
+import net.sf.jsqlparser.statement.cursor.CloseCursorStatement;
+import net.sf.jsqlparser.statement.cursor.DeclareCursorStatement;
+import net.sf.jsqlparser.statement.cursor.FetchCursorStatement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.drop.Drop;
import net.sf.jsqlparser.statement.execute.Execute;
import net.sf.jsqlparser.statement.grant.Grant;
+import net.sf.jsqlparser.statement.handler.HandlerStatement;
+import net.sf.jsqlparser.statement.lock.BackupLockStatement;
+import net.sf.jsqlparser.statement.lock.UnlockStatement;
import net.sf.jsqlparser.statement.merge.Merge;
import net.sf.jsqlparser.statement.refresh.RefreshMaterializedViewStatement;
+import net.sf.jsqlparser.statement.reindex.Reindex;
+import net.sf.jsqlparser.statement.resourcegroup.AlterResourceGroup;
+import net.sf.jsqlparser.statement.resourcegroup.CreateResourceGroup;
+import net.sf.jsqlparser.statement.resourcegroup.SetResourceGroup;
+import net.sf.jsqlparser.statement.role.ReassignOwned;
import net.sf.jsqlparser.statement.select.Fetch;
import net.sf.jsqlparser.statement.select.First;
import net.sf.jsqlparser.statement.select.KSQLWindow;
@@ -59,6 +83,7 @@
import net.sf.jsqlparser.statement.select.TableFunction;
import net.sf.jsqlparser.statement.select.Top;
import net.sf.jsqlparser.statement.select.UnPivot;
+import net.sf.jsqlparser.statement.securitylabel.SecurityLabel;
import net.sf.jsqlparser.statement.show.*;
import net.sf.jsqlparser.statement.truncate.Truncate;
import net.sf.jsqlparser.statement.update.Update;
@@ -450,6 +475,31 @@ public enum Feature {
*/
alterIndex,
+ /**
+ * MySQL and PostgreSQL "CREATE TABLESPACE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.tablespace.CreateTablespace
+ */
+ createTablespace,
+ /**
+ * MySQL and PostgreSQL "ALTER TABLESPACE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterTablespace
+ */
+ alterTablespace,
+ /**
+ * MySQL "CREATE SPATIAL REFERENCE SYSTEM" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.spatial.CreateSpatialReferenceSystem
+ */
+ createSpatialReferenceSystem,
+ /**
+ * MySQL "ALTER INSTANCE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterInstance
+ */
+ alterInstance,
+
/**
* SQL "ANALYZE" statement is allowed
@@ -458,6 +508,56 @@ public enum Feature {
*/
analyze,
+ /**
+ * MySQL/MariaDB "CHECK TABLE", "CHECKSUM TABLE", "OPTIMIZE TABLE" and "REPAIR TABLE" statements
+ * are allowed
+ *
+ * @see TableMaintenanceStatement
+ */
+ tableMaintenance,
+
+ /**
+ * MySQL "FLUSH" statement is allowed
+ *
+ * @see FlushStatement
+ */
+ flush,
+
+ /**
+ * MySQL "KILL" statement is allowed
+ *
+ * @see KillStatement
+ */
+ kill,
+
+ /**
+ * MySQL "HANDLER ... OPEN", "HANDLER ... READ" and "HANDLER ... CLOSE" statements are allowed
+ *
+ * @see HandlerStatement
+ */
+ handler,
+
+ /**
+ * PostgreSQL "VACUUM" statement is allowed
+ *
+ * @see VacuumStatement
+ */
+ vacuum,
+
+ /**
+ * PostgreSQL "CLUSTER" statement is allowed
+ *
+ * @see ClusterStatement
+ */
+ cluster,
+
+ /**
+ * PostgreSQL "CHECKPOINT" statement is allowed
+ *
+ * @see CheckpointStatement
+ */
+ checkpoint,
+
/**
* SQL "TRUNCATE" statement is allowed
*
@@ -482,7 +582,19 @@ public enum Feature {
*/
executeStatementImmediate,
+ /**
+ * MySQL "EXECUTE name USING @variable, ..." of a prepared statement is allowed
+ *
+ * @see Execute#getUsingVariables()
+ */
executeUsing,
+ /**
+ * "PREPARE" and "DEALLOCATE" of a prepared statement are allowed
+ *
+ * @see net.sf.jsqlparser.statement.PrepareStatement
+ * @see net.sf.jsqlparser.statement.DeallocateStatement
+ */
+ prepare, deallocate,
/**
* SQL "REPLACE" statement is allowed
*/
@@ -494,6 +606,24 @@ public enum Feature {
* @see Drop
*/
drop, dropTable, dropIndex, dropView, dropSchema, dropSequence, dropTableIfExists, dropIndexIfExists, dropViewIfExists, dropSchemaIfExists, dropSequenceIfExists,
+ /**
+ * Oracle "PURGE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.PurgeStatement
+ */
+ purge,
+ /**
+ * MySQL/MariaDB "PURGE BINARY LOGS" and MariaDB "PURGE MASTER LOGS" statements are allowed
+ *
+ * @see net.sf.jsqlparser.statement.PurgeStatement
+ */
+ purgeBinaryLogs,
+ /**
+ * PostgreSQL "REASSIGN OWNED BY ... TO ..." statement is allowed
+ *
+ * @see ReassignOwned
+ */
+ reassignOwned,
/**
* SQL "CREATE DATABASE" statement is allowed
@@ -501,6 +631,19 @@ public enum Feature {
* @see CreateDatabase
*/
createDatabase,
+ /**
+ * SQL "ALTER DATABASE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.database.AlterDatabase
+ */
+ alterDatabase,
+ /**
+ * "ALTER SESSION" and "ALTER SYSTEM" statements are allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterSession
+ * @see net.sf.jsqlparser.statement.alter.AlterSystemStatement
+ */
+ alterSession, alterSystem,
/**
* SQL "CREATE SCHEMA" statement is allowed
*
@@ -578,13 +721,28 @@ public enum Feature {
*
* @see CreateSequence
*/
- createSequence,
+ createSequence, createAccessMethod, createAccessMethodTable,
/** Publication and subscription definitions. */
+ createForeignDataWrapper, alterForeignDataWrapper, createServer, alterServer, createUserMapping, alterUserMapping,
+ /**
+ * PostgreSQL "IMPORT FOREIGN SCHEMA" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.foreign.ImportForeignSchema
+ */
+ importForeignSchema,
+
+ createRule, notifyStatement, createTextSearchConfiguration, alterTextSearchConfiguration, createCollation, alterCollation,
+
createPublication, alterPublication, createSubscription, alterSubscription,
/**
* Structured type, domain and extension statements.
*/
createType, alterType, createDomain, alterDomain, createExtension, alterExtension,
+ /**
+ * PostgreSQL "CREATE POLICY", "ALTER POLICY", "CREATE STATISTICS" and "ALTER STATISTICS"
+ * statements are allowed
+ */
+ createPolicy, alterPolicy, createStatistics, alterStatistics,
/**
* SQL "CREATE SYNONYM" statement is allowed
*
@@ -595,12 +753,169 @@ public enum Feature {
* SQL "CREATE TRIGGER" statement is allowed
*/
createTrigger,
+ /**
+ * MySQL/MariaDB "CREATE EVENT" and "ALTER EVENT" statements are allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.event.CreateEvent
+ * @see net.sf.jsqlparser.statement.create.event.AlterEvent
+ */
+ createEvent, alterEvent,
+ /**
+ * PostgreSQL "CREATE EVENT TRIGGER" and "ALTER EVENT TRIGGER" statements are allowed
+ *
+ * @see CreateEventTrigger
+ * @see AlterEventTrigger
+ */
+ createEventTrigger, alterEventTrigger,
+ /**
+ * PostgreSQL "REINDEX" statement is allowed; "REINDEX … CONCURRENTLY" additionally requires
+ * {@link #reindexConcurrently}
+ *
+ * @see Reindex
+ */
+ reindex, reindexConcurrently,
+ /**
+ * PostgreSQL "SECURITY LABEL" statement is allowed
+ *
+ * @see SecurityLabel
+ */
+ securityLabel,
/**
* SQL "COMMIT" statement is allowed
*
* @see Commit
*/
commit,
+ /** SQL "ROLLBACK" statement is allowed */
+ rollback,
+ /** START TRANSACTION and dialect-specific BEGIN transaction statements. */
+ startTransaction,
+ /** SAVEPOINT statements. */
+ savepoint,
+ /** RELEASE [SAVEPOINT] statements. */
+ releaseSavepoint,
+ /** Explicit AND [NO] CHAIN transaction completion. */
+ transactionChain,
+ /** Isolation level specified directly on BEGIN or START TRANSACTION. */
+ transactionIsolationLevel,
+ /** PostgreSQL [NOT] DEFERRABLE transaction characteristic. */
+ transactionDeferrable,
+ /** MySQL WITH CONSISTENT SNAPSHOT transaction characteristic. */
+ transactionConsistentSnapshot,
+ /** MySQL [NO] RELEASE after COMMIT or ROLLBACK. */
+ transactionRelease,
+ /** PostgreSQL END and ABORT, the alternative spellings of COMMIT and ROLLBACK. */
+ transactionEndAbort,
+ /**
+ * SET TRANSACTION characteristics
+ *
+ * @see SetTransactionStatement
+ */
+ setTransaction,
+ /** MySQL SET GLOBAL TRANSACTION. */
+ setTransactionGlobal,
+ /** MySQL SET PERSIST TRANSACTION and SET PERSIST_ONLY TRANSACTION. */
+ setTransactionPersist,
+ /** PostgreSQL SET SESSION CHARACTERISTICS AS TRANSACTION. */
+ setTransactionSessionCharacteristics,
+ /** PostgreSQL SET TRANSACTION SNAPSHOT. */
+ setTransactionSnapshot,
+ /**
+ * SET CONSTRAINTS {ALL | names} {DEFERRED | IMMEDIATE}
+ *
+ * @see SetConstraintsStatement
+ */
+ setConstraints,
+ /**
+ * PostgreSQL two-phase commit: PREPARE TRANSACTION, COMMIT PREPARED and ROLLBACK PREPARED
+ *
+ * @see PrepareTransactionStatement
+ */
+ twoPhaseCommit,
+ /**
+ * MySQL and MariaDB XA statements: XA START, END, PREPARE, COMMIT, ROLLBACK and RECOVER
+ *
+ * @see XaStatement
+ */
+ xa,
+ /**
+ * MySQL and MariaDB INSTALL PLUGIN and UNINSTALL PLUGIN
+ *
+ * @see PluginStatement
+ */
+ installPlugin,
+ /**
+ * MySQL INSTALL COMPONENT and UNINSTALL COMPONENT
+ *
+ * @see PluginStatement
+ */
+ installComponent,
+ /**
+ * SQL "LOCK TABLE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.lock.LockStatement
+ */
+ lock,
+ /**
+ * MySQL/MariaDB "UNLOCK TABLES" statement is allowed
+ *
+ * @see UnlockStatement
+ */
+ unlockTables,
+ /**
+ * MySQL "LOCK INSTANCE FOR BACKUP" and "UNLOCK INSTANCE" statements are allowed
+ *
+ * @see BackupLockStatement
+ */
+ backupLock,
+ /**
+ * MySQL "CREATE RESOURCE GROUP" statement is allowed
+ *
+ * @see CreateResourceGroup
+ */
+ createResourceGroup,
+ /**
+ * MySQL "ALTER RESOURCE GROUP" statement is allowed
+ *
+ * @see AlterResourceGroup
+ */
+ alterResourceGroup,
+ /**
+ * MySQL "SET RESOURCE GROUP" statement is allowed
+ *
+ * @see SetResourceGroup
+ */
+ setResourceGroup,
+ /**
+ * MySQL "CHANGE REPLICATION SOURCE TO" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.replication.ChangeReplicationSourceStatement
+ */
+ changeReplicationSource,
+ /**
+ * MySQL "CHANGE REPLICATION FILTER" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.replication.ChangeReplicationFilterStatement
+ */
+ changeReplicationFilter,
+ /**
+ * MySQL "START REPLICA" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.replication.StartReplicaStatement
+ */
+ startReplica,
+ /**
+ * MySQL "STOP REPLICA" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.replication.StopReplicaStatement
+ */
+ stopReplica,
+ /**
+ * MySQL "RESET BINARY LOGS AND GTIDS" and "RESET REPLICA" statements are allowed
+ *
+ * @see net.sf.jsqlparser.statement.replication.ResetReplicationStatement
+ */
+ resetReplication,
/**
* SQL "COMMENT ON" statement is allowed
*
@@ -623,6 +938,33 @@ public enum Feature {
/** Additional structured catalog targets of COMMENT ON. */
commentOnIndex, commentOnSchema, commentOnSequence, commentOnDomain, commentOnType, commentOnMaterializedView, commentOnFunction, commentOnConstraint,
+ /** COMMENT ON TRIGGER, POLICY or RULE within a table. */
+ commentOnTrigger, commentOnPolicy, commentOnRule,
+
+ /** COMMENT ON PROCEDURE, ROUTINE, AGGREGATE or CAST. */
+ commentOnProcedure, commentOnRoutine, commentOnAggregate, commentOnCast,
+
+ /** COMMENT ON COLLATION, FOREIGN TABLE or STATISTICS. */
+ commentOnCollation, commentOnForeignTable, commentOnStatistics,
+
+ /** COMMENT ON DATABASE, ROLE or TABLESPACE. */
+ commentOnDatabase, commentOnRole, commentOnTablespace,
+
+ /** COMMENT ON ACCESS METHOD, EXTENSION, FOREIGN DATA WRAPPER, LANGUAGE or SERVER. */
+ commentOnAccessMethod, commentOnExtension, commentOnForeignDataWrapper, commentOnLanguage, commentOnServer,
+
+ /** COMMENT ON EVENT TRIGGER, PUBLICATION or SUBSCRIPTION. */
+ commentOnEventTrigger, commentOnPublication, commentOnSubscription,
+
+ /** COMMENT ON OPERATOR, OPERATOR CLASS or OPERATOR FAMILY. */
+ commentOnOperator, commentOnOperatorClass, commentOnOperatorFamily,
+
+ /** COMMENT ON CONVERSION, LARGE OBJECT or TRANSFORM. */
+ commentOnConversion, commentOnLargeObject, commentOnTransform,
+
+ /** COMMENT ON TEXT SEARCH CONFIGURATION, DICTIONARY, PARSER or TEMPLATE. */
+ commentOnTextSearchConfiguration, commentOnTextSearchDictionary, commentOnTextSearchParser, commentOnTextSearchTemplate,
+
/**
* SQL "DESCRIBE" statement is allowed
*
@@ -659,6 +1001,25 @@ public enum Feature {
* @see ShowIndexStatement
*/
showIndex,
+ /**
+ * MySQL/MariaDB "SHOW TABLE STATUS" statement is allowed
+ *
+ * @see ShowTableStatusStatement
+ */
+ showTableStatus,
+ /**
+ * MySQL/MariaDB "SHOW CREATE" statement is allowed
+ *
+ * @see ShowCreateStatement
+ */
+ showCreate,
+ /**
+ * The MySQL/MariaDB "SHOW" statements of server settings, state and object lists, such as "SHOW
+ * VARIABLES", "SHOW GRANTS" or "SHOW BINLOG EVENTS"
+ *
+ * @see MySqlShowStatement
+ */
+ mySqlShow,
/**
* @see UseStatement
*/
@@ -669,6 +1030,18 @@ public enum Feature {
* @see Grant
*/
grant, revoke, createRole, alterRole, alterDefaultPrivileges,
+ /**
+ * MySQL/MariaDB account management: "CREATE USER", "ALTER USER", "RENAME USER", "SET ROLE",
+ * "SET DEFAULT ROLE" and "SET PASSWORD"
+ *
+ * @see net.sf.jsqlparser.statement.create.user.CreateUser
+ * @see net.sf.jsqlparser.statement.alter.AlterUser
+ * @see net.sf.jsqlparser.statement.alter.RenameUser
+ * @see net.sf.jsqlparser.statement.SetRoleStatement
+ * @see net.sf.jsqlparser.statement.SetDefaultRoleStatement
+ * @see net.sf.jsqlparser.statement.SetPasswordStatement
+ */
+ createUser, alterUser, renameUser, setRole, setDefaultRole, setPassword,
/**
* @see Function
*/
@@ -687,6 +1060,150 @@ public enum Feature {
functionalStatement,
alterFunction, alterProcedure, createOrAlterRoutine,
+ /**
+ * PostgreSQL "ALTER ROUTINE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterRoutine
+ */
+ alterRoutine,
+ /**
+ * PostgreSQL "ALTER TRIGGER" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterTrigger
+ */
+ alterTrigger,
+ /**
+ * PostgreSQL "ALTER RULE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterRule
+ */
+ alterRule,
+ /**
+ * PostgreSQL "CREATE CAST" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.cast.CreateCast
+ */
+ createCast,
+ /**
+ * PostgreSQL "CREATE TRANSFORM" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.transform.CreateTransform
+ */
+ createTransform,
+ /**
+ * PostgreSQL "CREATE CONVERSION" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.conversion.CreateConversion
+ */
+ createConversion,
+ /**
+ * PostgreSQL "ALTER CONVERSION" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterConversion
+ */
+ alterConversion,
+ /**
+ * PostgreSQL CREATE metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.create.language.CreateLanguage
+ */
+ createLanguage,
+ /**
+ * PostgreSQL ALTER metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterLanguage
+ */
+ alterLanguage,
+ /**
+ * PostgreSQL ALTER metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterLargeObject
+ */
+ alterLargeObject,
+ /**
+ * PostgreSQL CREATE metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.create.textsearch.CreateTextSearchDictionary
+ */
+ createTextSearchDictionary,
+ /**
+ * PostgreSQL ALTER metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterTextSearchDictionary
+ */
+ alterTextSearchDictionary,
+ /**
+ * PostgreSQL CREATE metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.create.textsearch.CreateTextSearchParser
+ */
+ createTextSearchParser,
+ /**
+ * PostgreSQL ALTER metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterTextSearchParser
+ */
+ alterTextSearchParser,
+ /**
+ * PostgreSQL CREATE metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.create.textsearch.CreateTextSearchTemplate
+ */
+ createTextSearchTemplate,
+ /**
+ * PostgreSQL ALTER metadata statement is allowed.
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterTextSearchTemplate
+ */
+ alterTextSearchTemplate,
+ /**
+ * PostgreSQL "CREATE OPERATOR" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.operator.CreateOperator
+ */
+ createOperator,
+ /**
+ * PostgreSQL "CREATE OPERATOR CLASS" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.operator.CreateOperatorClass
+ */
+ createOperatorClass,
+ /**
+ * PostgreSQL "CREATE OPERATOR FAMILY" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.operator.CreateOperatorFamily
+ */
+ createOperatorFamily,
+ /**
+ * PostgreSQL "CREATE AGGREGATE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.create.aggregate.CreateAggregate
+ */
+ createAggregate,
+ /**
+ * PostgreSQL "ALTER OPERATOR" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterOperator
+ */
+ alterOperator,
+ /**
+ * PostgreSQL "ALTER OPERATOR CLASS" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterOperatorClass
+ */
+ alterOperatorClass,
+ /**
+ * PostgreSQL "ALTER OPERATOR FAMILY" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterOperatorFamily
+ */
+ alterOperatorFamily,
+ /**
+ * PostgreSQL "ALTER AGGREGATE" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.alter.AlterAggregate
+ */
+ alterAggregate,
/**
* SQL block starting with "BEGIN" and ends with "END" statement is allowed
*
@@ -697,6 +1214,24 @@ public enum Feature {
* @see DeclareStatement
*/
declare,
+ /**
+ * PostgreSQL "DECLARE name CURSOR FOR query" statement is allowed
+ *
+ * @see DeclareCursorStatement
+ */
+ declareCursor,
+ /**
+ * PostgreSQL "FETCH" and "MOVE" statements of a cursor are allowed
+ *
+ * @see FetchCursorStatement
+ */
+ fetchCursor,
+ /**
+ * PostgreSQL "CLOSE" statement of a cursor is allowed
+ *
+ * @see CloseCursorStatement
+ */
+ closeCursor,
/** SQL Server local table variables in queries and DML targets. */
tableVariable,
@@ -704,12 +1239,32 @@ public enum Feature {
* @see SetStatement
*/
set,
+ /** PostgreSQL SET configuration_parameter TO value. */
+ setAssignmentTo,
/** SQL Server SET option [, option] ON | OFF. */
sqlServerSetOptions,
/**
* @see ResetStatement
*/
reset,
+ /**
+ * PostgreSQL "DISCARD" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.DiscardStatement
+ */
+ discard,
+ /**
+ * PostgreSQL "LISTEN" and "UNLISTEN" statements are allowed
+ *
+ * @see net.sf.jsqlparser.statement.notify.ListenStatement
+ */
+ listen,
+ /**
+ * MySQL "RESET PERSIST" statement is allowed
+ *
+ * @see ResetStatement#isPersist()
+ */
+ resetPersist,
/**
* @see Pivot
*/
@@ -794,7 +1349,7 @@ public enum Feature {
// MYSQL
- mySqlHintStraightJoin, mysqlSqlCacheFlag, mysqlCalcFoundRows,
+ mySqlHintStraightJoin, mysqlSqlCacheFlag, mysqlCalcFoundRows, mysqlSelectModifiers,
// SQLSERVER
@@ -816,6 +1371,14 @@ public enum Feature {
/** Enables legacy GROUP BY ordering with the MYSQL dialect; disabled by default. */
allowLegacyMySqlGroupBy(false),
+ /**
+ * Target MySQL version for executable comments, encoded as major * 10000 + minor * 100 + patch.
+ * A negative value leaves the version unspecified: conditional comments then fail instead of
+ * silently discarding SQL. Only used with the MYSQL dialect; unversioned comments need no
+ * value.
+ */
+ mySqlServerVersion(-1),
+
// PERFORMANCE
/**
@@ -863,6 +1426,19 @@ public enum Feature {
*/
allowHashLineComments(false),
+ /**
+ * treats three consecutive newlines as a statement separator (enabled by default). When
+ * disabled, blank lines are plain whitespace, so a statement containing them is parsed whole
+ * instead of ending, or failing to parse, at the first run of blank lines
+ */
+ allowBlankLinesAsStatementSeparator(true),
+
+ /**
+ * allows digit separators in numeric literals, e.g. {@code 1_000_000} (DuckDB, PostgreSQL 16);
+ * disabled by default, where MySQL reads {@code 2024_01} as an identifier
+ */
+ allowDigitSeparators(false),
+
/**
* allows sub selects without parentheses, e.g. `select * from dual where 1 = select 1`
*/
@@ -881,10 +1457,40 @@ public enum Feature {
imprt,
/**
- * "EXPORT"
+ * "EXPORT" and BigQuery "EXPORT DATA"
*/
export,
+ /**
+ * PostgreSQL and DuckDB "COPY", BigQuery and MySQL "LOAD DATA" and MySQL "LOAD XML" statements
+ * are allowed
+ *
+ * @see net.sf.jsqlparser.statement.CopyStatement
+ * @see net.sf.jsqlparser.statement.load.LoadDataStatement
+ * @see net.sf.jsqlparser.statement.load.MySqlLoadDataStatement
+ */
+ copy, loadData,
+
+ /**
+ * DuckDB "ATTACH", "DETACH", "CONNECT", "DISCONNECT", "PRAGMA", "INSTALL", "LOAD", "CREATE
+ * MACRO" and "CREATE EXTENSION REPOSITORY" statements are allowed
+ */
+ attach, detach, connect, disconnect, pragma, installExtension, loadExtension, createMacro, createExtensionRepository,
+
+ /**
+ * BigQuery "ASSERT" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.AssertStatement
+ */
+ assertStatement,
+
+ /**
+ * "SESSION" statement is allowed
+ *
+ * @see net.sf.jsqlparser.statement.SessionStatement
+ */
+ session,
+
/**
* MySQL allows a ',' as a separator between key and value entries. We allow that by default,
* but it can be disabled here
diff --git a/src/main/java/net/sf/jsqlparser/schema/Column.java b/src/main/java/net/sf/jsqlparser/schema/Column.java
index 33240ac52a..3bb06de241 100644
--- a/src/main/java/net/sf/jsqlparser/schema/Column.java
+++ b/src/main/java/net/sf/jsqlparser/schema/Column.java
@@ -49,10 +49,14 @@ public Column(List nameParts) {
}
public Column(List nameParts, List delimiters) {
- this(
- nameParts.size() > 1 ? new Table(nameParts.subList(0, nameParts.size() - 1),
- delimiters.subList(0, delimiters.size() - 1)) : null,
- nameParts.get(nameParts.size() - 1));
+ if (nameParts.size() > 1) {
+ setTable(new Table(nameParts.subList(0, nameParts.size() - 1),
+ delimiters.subList(0, delimiters.size() - 1)));
+ // The final component is already separated from the table name.
+ setName(nameParts.get(nameParts.size() - 1), false);
+ } else {
+ setColumnName(nameParts.get(0));
+ }
setTableDelimiter(delimiters.isEmpty() ? "." : delimiters.get(delimiters.size() - 1));
}
@@ -149,36 +153,25 @@ public void setColumnName(String name) {
}
public void setName(String name, boolean splitNamesOnDelimiter) {
- if (MultiPartName.isQuoted(name) && name.contains(".") && splitNamesOnDelimiter) {
- String[] parts = MultiPartName.unquote(name).split("\\.");
- switch (parts.length) {
- case 3:
- this.table = new Table("\"" + parts[0] + "\".\"" + parts[1] + "\"");
- this.columnName = "\"" + parts[2] + "\"";
- break;
- case 2:
- this.table = new Table("\"" + parts[0] + "\"");
- this.columnName = "\"" + parts[1] + "\"";
- break;
- case 1:
- this.columnName = "\"" + parts[0] + "\"";
- break;
- default:
- throw new RuntimeException("Invalid column name: " + name);
+ if (name.contains(".") && splitNamesOnDelimiter) {
+ List parts = splitName(name);
+ if (parts.size() == 1 && MultiPartName.isQuoted(name)) {
+ parts.clear();
+ for (String identifier : MultiPartName.unquote(name).split("\\.")) {
+ parts.add("\"" + identifier + "\"");
+ }
}
- } else if (name.contains(".") && splitNamesOnDelimiter) {
- String[] parts = MultiPartName.unquote(name).split("\\.");
- switch (parts.length) {
+ switch (parts.size()) {
case 3:
- this.table = new Table(parts[0] + "." + parts[1]);
- this.columnName = parts[2];
+ this.table = new Table(parts.subList(0, 2));
+ this.columnName = parts.get(2);
break;
case 2:
- this.table = new Table(parts[0]);
- this.columnName = parts[1];
+ this.table = new Table(parts.get(0), false);
+ this.columnName = parts.get(1);
break;
case 1:
- this.columnName = parts[0];
+ this.columnName = parts.get(0);
break;
default:
throw new RuntimeException("Invalid column name: " + name);
@@ -188,6 +181,34 @@ public void setName(String name, boolean splitNamesOnDelimiter) {
}
}
+ private static List splitName(String name) {
+ List parts = new ArrayList<>();
+ int start = 0;
+ char quote = 0;
+ for (int i = 0; i < name.length(); i++) {
+ char ch = name.charAt(i);
+ if (quote != 0) {
+ if (ch == quote) {
+ if (i + 1 < name.length() && name.charAt(i + 1) == quote) {
+ i++;
+ } else {
+ quote = 0;
+ }
+ }
+ } else if (ch == '"' || ch == '`' || ch == '[') {
+ quote = ch == '[' ? ']' : ch;
+ } else if (ch == '.') {
+ parts.add(name.substring(start, i));
+ start = i + 1;
+ }
+ }
+ parts.add(name.substring(start));
+ while (!parts.isEmpty() && parts.get(parts.size() - 1).isEmpty()) {
+ parts.remove(parts.size() - 1);
+ }
+ return parts;
+ }
+
public String getTableDelimiter() {
return tableDelimiter;
}
diff --git a/src/main/java/net/sf/jsqlparser/schema/MultiPartName.java b/src/main/java/net/sf/jsqlparser/schema/MultiPartName.java
index ce954780d7..b49e58384e 100644
--- a/src/main/java/net/sf/jsqlparser/schema/MultiPartName.java
+++ b/src/main/java/net/sf/jsqlparser/schema/MultiPartName.java
@@ -23,13 +23,34 @@ public interface MultiPartName {
* @return the pure identifier without quotes
*/
static String unquote(String quotedIdentifier) {
- return quotedIdentifier != null
- ? LEADING_TRAILING_QUOTES_PATTERN.matcher(quotedIdentifier).replaceAll("")
- : null;
+ if (quotedIdentifier == null) {
+ return null;
+ }
+ // same result as LEADING_TRAILING_QUOTES_PATTERN.matcher(..).replaceAll(""), but linear:
+ // the regex retries its trailing alternative at every offset of a run of quotes
+ int start = 0;
+ int end = quotedIdentifier.length();
+ while (start < end && isLeadingQuote(quotedIdentifier.charAt(start))) {
+ start++;
+ }
+ while (end > start && isTrailingQuote(quotedIdentifier.charAt(end - 1))) {
+ end--;
+ }
+ return quotedIdentifier.substring(start, end);
}
static boolean isQuoted(String identifier) {
- return identifier != null && LEADING_TRAILING_QUOTES_PATTERN.matcher(identifier).find();
+ return identifier != null && !identifier.isEmpty()
+ && (isLeadingQuote(identifier.charAt(0))
+ || isTrailingQuote(identifier.charAt(identifier.length() - 1)));
+ }
+
+ private static boolean isLeadingQuote(char c) {
+ return c == '"' || c == '[' || c == '`';
+ }
+
+ private static boolean isTrailingQuote(char c) {
+ return c == '"' || c == ']' || c == '`';
}
String getFullyQualifiedName();
diff --git a/src/main/java/net/sf/jsqlparser/schema/Sequence.java b/src/main/java/net/sf/jsqlparser/schema/Sequence.java
index efff62a970..ff7cd66a55 100644
--- a/src/main/java/net/sf/jsqlparser/schema/Sequence.java
+++ b/src/main/java/net/sf/jsqlparser/schema/Sequence.java
@@ -187,7 +187,7 @@ public Sequence addParameters(Collection extends Parameter> parameters) {
* The available parameters to a sequence
*/
public enum ParameterType {
- INCREMENT_BY, INCREMENT, START_WITH, START, RESTART_WITH, MAXVALUE, NOMAXVALUE, MINVALUE, NOMINVALUE, CYCLE, NOCYCLE, CACHE, NOCACHE, ORDER, NOORDER, KEEP, NOKEEP, SESSION, GLOBAL, NO_MINVALUE, NO_MAXVALUE, NO_CYCLE;
+ INCREMENT_BY, INCREMENT, START_WITH, START, RESTART_WITH, MAXVALUE, NOMAXVALUE, MINVALUE, NOMINVALUE, CYCLE, NOCYCLE, CACHE, NOCACHE, ORDER, NOORDER, KEEP, NOKEEP, SESSION, GLOBAL, NO_MINVALUE, NO_MAXVALUE, NO_CYCLE, SEQUENCE_NAME, LOGGED, UNLOGGED;
public static ParameterType from(String type) {
return Enum.valueOf(ParameterType.class, type.toUpperCase(Locale.ROOT));
@@ -201,6 +201,7 @@ public static class Parameter implements java.io.Serializable {
private final ParameterType option;
private Long value;
+ private Sequence sequenceName;
public Parameter(ParameterType option) {
this.option = option;
@@ -214,6 +215,20 @@ public ParameterType getOption() {
return option;
}
+ /** The sequence named by an identity declaration's SEQUENCE NAME option. */
+ public Sequence getSequenceName() {
+ return sequenceName;
+ }
+
+ public void setSequenceName(Sequence sequenceName) {
+ this.sequenceName = sequenceName;
+ }
+
+ public Parameter withSequenceName(Sequence sequenceName) {
+ setSequenceName(sequenceName);
+ return this;
+ }
+
@Override
public String toString() {
return formatParameter();
@@ -225,6 +240,8 @@ public void setValue(Long value) {
public String formatParameter() {
switch (option) {
+ case SEQUENCE_NAME:
+ return "SEQUENCE NAME " + sequenceName.getFullyQualifiedName();
case INCREMENT_BY:
return prefix("INCREMENT BY");
case INCREMENT:
diff --git a/src/main/java/net/sf/jsqlparser/schema/Table.java b/src/main/java/net/sf/jsqlparser/schema/Table.java
index 0e23b28a9c..bbf9f4536a 100644
--- a/src/main/java/net/sf/jsqlparser/schema/Table.java
+++ b/src/main/java/net/sf/jsqlparser/schema/Table.java
@@ -60,7 +60,7 @@ public class Table extends ASTNodeAccessImpl
private UnPivot unpivot;
- private MySQLIndexHint mysqlHints;
+ private List mysqlIndexHints;
private SQLServerHints sqlServerHints;
@@ -411,8 +411,13 @@ public void setUnPivot(UnPivot unpivot) {
this.unpivot = unpivot;
}
+ /**
+ * Returns the first MySQL index hint, or {@code null}. Use {@link #getIndexHints()} for a table
+ * with several hints.
+ */
public MySQLIndexHint getIndexHint() {
- return mysqlHints;
+ return mysqlIndexHints == null || mysqlIndexHints.isEmpty() ? null
+ : mysqlIndexHints.get(0);
}
public Table withHint(MySQLIndexHint hint) {
@@ -420,8 +425,46 @@ public Table withHint(MySQLIndexHint hint) {
return this;
}
+ /**
+ * Replaces the MySQL index hints with the given hint, or removes them for {@code null}.
+ */
public void setHint(MySQLIndexHint hint) {
- this.mysqlHints = hint;
+ this.mysqlIndexHints = hint == null ? null : new ArrayList<>(Collections.singleton(hint));
+ }
+
+ /**
+ * Returns the MySQL index hints in their order, for example
+ * {@code USE INDEX (i1) IGNORE INDEX FOR ORDER BY (i2)}, or {@code null} when there are none.
+ */
+ public List getIndexHints() {
+ return mysqlIndexHints;
+ }
+
+ public void setIndexHints(List indexHints) {
+ this.mysqlIndexHints = indexHints;
+ }
+
+ public Table withIndexHints(List indexHints) {
+ setIndexHints(indexHints);
+ return this;
+ }
+
+ public Table addIndexHint(MySQLIndexHint hint) {
+ if (mysqlIndexHints == null) {
+ mysqlIndexHints = new ArrayList<>();
+ }
+ mysqlIndexHints.add(hint);
+ return this;
+ }
+
+ /** Appends the MySQL index hints, each with a leading space, in their order. */
+ public StringBuilder appendIndexHintsTo(StringBuilder builder) {
+ if (mysqlIndexHints != null) {
+ for (MySQLIndexHint hint : mysqlIndexHints) {
+ hint.appendTo(builder);
+ }
+ }
+ return builder;
}
public SQLServerHints getSqlServerHints() {
@@ -468,9 +511,7 @@ public StringBuilder appendTo(StringBuilder builder) {
builder.append(" ").append(unpivot);
}
- if (mysqlHints != null) {
- builder.append(mysqlHints);
- }
+ appendIndexHintsTo(builder);
if (sqlServerHints != null) {
builder.append(sqlServerHints);
diff --git a/src/main/java/net/sf/jsqlparser/schema/TableReference.java b/src/main/java/net/sf/jsqlparser/schema/TableReference.java
new file mode 100644
index 0000000000..2d64aa10b1
--- /dev/null
+++ b/src/main/java/net/sf/jsqlparser/schema/TableReference.java
@@ -0,0 +1,115 @@
+/*-
+ * #%L
+ * JSQLParser library
+ * %%
+ * Copyright (C) 2004 - 2026 JSQLParser
+ * %%
+ * Dual licensed under GNU LGPL 2.1 or Apache License 2.0
+ * #L%
+ */
+package net.sf.jsqlparser.schema;
+
+import java.io.Serializable;
+
+/**
+ * A relation target with optional PostgreSQL inheritance scope, shared by LOCK, TRUNCATE and the
+ * targets of UPDATE, DELETE and MERGE.
+ */
+public class TableReference implements Serializable {
+ private Table table;
+ private boolean only;
+ private boolean includeDescendants;
+ private boolean parenthesized;
+
+ public TableReference(Table table) {
+ this.table = table;
+ }
+
+ public Table getTable() {
+ return table;
+ }
+
+ public void setTable(Table table) {
+ this.table = table;
+ }
+
+ public boolean isOnly() {
+ return only;
+ }
+
+ public void setOnly(boolean only) {
+ this.only = only;
+ if (only) {
+ includeDescendants = false;
+ } else {
+ parenthesized = false;
+ }
+ }
+
+ public boolean isIncludeDescendants() {
+ return includeDescendants;
+ }
+
+ public void setIncludeDescendants(boolean includeDescendants) {
+ this.includeDescendants = includeDescendants;
+ if (includeDescendants) {
+ only = false;
+ parenthesized = false;
+ }
+ }
+
+ public boolean isParenthesized() {
+ return parenthesized;
+ }
+
+ public void setParenthesized(boolean parenthesized) {
+ this.parenthesized = parenthesized;
+ if (parenthesized) {
+ only = true;
+ includeDescendants = false;
+ }
+ }
+
+ public StringBuilder appendTo(StringBuilder builder) {
+ if (only) {
+ builder.append("ONLY ");
+ }
+ if (parenthesized) {
+ builder.append('(');
+ }
+ builder.append(table.getFullyQualifiedName());
+ if (parenthesized) {
+ builder.append(')');
+ }
+ if (includeDescendants) {
+ builder.append(" *");
+ }
+ return builder;
+ }
+
+ /**
+ * Appends the target of UPDATE, DELETE or MERGE (PostgreSQL's relation_expr_opt_alias): the
+ * inheritance scope surrounds the table name and the alias of the table follows it. A target
+ * without a scope is the table as it renders itself, with its alias and hints.
+ */
+ public StringBuilder appendWithAliasTo(StringBuilder builder) {
+ if (!only && !includeDescendants || table == null) {
+ return builder.append(table);
+ }
+ appendTo(builder);
+ if (table.getAlias() != null) {
+ builder.append(table.getAlias());
+ }
+ return builder;
+ }
+
+ /** Whether ONLY or * describes the inheritance scope of the table. */
+ public boolean hasInheritanceScope() {
+ return only || includeDescendants;
+ }
+
+ @Override
+ public String toString() {
+ return appendTo(new StringBuilder()).toString();
+ }
+}
diff --git a/src/main/java/net/sf/jsqlparser/statement/AssertStatement.java b/src/main/java/net/sf/jsqlparser/statement/AssertStatement.java
index 1e5a742982..58a294bb5f 100644
--- a/src/main/java/net/sf/jsqlparser/statement/AssertStatement.java
+++ b/src/main/java/net/sf/jsqlparser/statement/AssertStatement.java
@@ -11,6 +11,7 @@
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
+import net.sf.jsqlparser.parser.ASTNodeAccessImpl;
import java.util.function.Consumer;
@@ -22,7 +23,7 @@
* "https://cloud.google.com/bigquery/docs/reference/standard-sql/debugging-statements">Debugging
* statements