@@ -25,6 +25,9 @@ public final class StringValue extends ASTNodeAccessImpl implements Expression {
2525 public static final List<String> ALLOWED_PREFIXES =
2626 Arrays.asList("N", "U", "E", "R", "B", "RB", "_utf8", "Q");
2727
28+ /** The prefix of a PostgreSQL Unicode escape string, as in {@code U&'\0041'}. */
29+ private static final String UNICODE_ESCAPE_PREFIX = "U&";
30+
2831 /**
2932 * How a backslash in the literal body was read. The parser records the escaping of the
3033 * configuration that lexed the literal; constructed values default to {@link #STANDARD}.
@@ -35,13 +38,21 @@ public enum Escaping {
3538 /** MySQL/MariaDB backslash escapes, for example {@code \n}, {@code \'} and {@code \\}. */
3639 MYSQL_BACKSLASH,
3740 /** PostgreSQL escape string escapes, for example {@code E'\n'} and {@code E'\x41'}. */
38- POSTGRESQL_ESCAPE_STRING
41+ POSTGRESQL_ESCAPE_STRING,
42+ /**
43+ * PostgreSQL Unicode escapes of a {@code U&'...'} string: the escape character followed by
44+ * four hexadecimal digits or by {@code +} and six, and a doubled escape character. The
45+ * escape character is a backslash unless {@link #getUnicodeEscapeCharacter()} names another
46+ * one.
47+ */
48+ POSTGRESQL_UNICODE_ESCAPE
3949 }
4050
4151 private String value = "";
4252 private String prefix = null;
4353 private String quoteStr = "'";
4454 private Escaping escaping = Escaping.STANDARD;
55+ private Character unicodeEscapeCharacter = null;
4556
4657 public StringValue() {
4758 // empty constructor
@@ -70,6 +81,10 @@ public StringValue(String escapedValue) {
7081 return;
7182 }
7283
84+ if (readUnicodeEscapeString(escapedValue)) {
85+ return;
86+ }
87+
7388 if (escapedValue.length() > 2) {
7489 for (String p : ALLOWED_PREFIXES) {
7590 if (escapedValue.length() > p.length()
@@ -85,6 +100,46 @@ public StringValue(String escapedValue) {
85100 value = escapedValue;
86101 }
87102
103+ /**
104+ * Reads {@code U&'body'} with an optional {@code UESCAPE 'c'} clause. Returns false, leaving
105+ * this value unchanged, when the text has another shape.
106+ */
107+ private boolean readUnicodeEscapeString(String text) {
108+ if (!text.regionMatches(true, 0, UNICODE_ESCAPE_PREFIX + "'", 0, 3)) {
109+ return false;
110+ }
111+ int close = 3;
112+ while (close < text.length()) {
113+ if (text.charAt(close) != '\'') {
114+ close++;
115+ } else if (close + 1 < text.length() && text.charAt(close + 1) == '\'') {
116+ close += 2;
117+ } else {
118+ break;
119+ }
120+ }
121+ if (close >= text.length()) {
122+ return false;
123+ }
124+ String clause = text.substring(close + 1).trim();
125+ Character escape = null;
126+ if (!clause.isEmpty()) {
127+ if (!clause.regionMatches(true, 0, "UESCAPE", 0, 7)) {
128+ return false;
129+ }
130+ String quoted = clause.substring(7).trim();
131+ if (quoted.length() != 3 || quoted.charAt(0) != '\'' || quoted.charAt(2) != '\'') {
132+ return false;
133+ }
134+ escape = quoted.charAt(1);
135+ }
136+ prefix = UNICODE_ESCAPE_PREFIX;
137+ value = text.substring(3, close);
138+ escaping = Escaping.POSTGRESQL_UNICODE_ESCAPE;
139+ unicodeEscapeCharacter = escape;
140+ return true;
141+ }
142+
88143 /**
89144 * Returns the opening PostgreSQL dollar-quote delimiter, or null if there is none. A tag
90145 * follows unquoted identifier rules, excluding dollar signs. This method does not require the
@@ -149,17 +204,47 @@ public StringValue withEscaping(Escaping escaping) {
149204 return this;
150205 }
151206
207+ /**
208+ * Returns the escape character named by the {@code UESCAPE} clause of a PostgreSQL Unicode
209+ * escape string, or null when the literal has no such clause and the escape character is a
210+ * backslash.
211+ */
212+ public Character getUnicodeEscapeCharacter() {
213+ return unicodeEscapeCharacter;
214+ }
215+
216+ /**
217+ * Sets the escape character rendered as {@code UESCAPE 'c'} after the literal; null removes the
218+ * clause. It applies to {@link Escaping#POSTGRESQL_UNICODE_ESCAPE} values, whose
219+ * {@link #getNotExcapedValue()} rejects a character that PostgreSQL rejects.
220+ */
221+ public void setUnicodeEscapeCharacter(Character unicodeEscapeCharacter) {
222+ this.unicodeEscapeCharacter = unicodeEscapeCharacter;
223+ }
224+
225+ public StringValue withUnicodeEscapeCharacter(Character unicodeEscapeCharacter) {
226+ setUnicodeEscapeCharacter(unicodeEscapeCharacter);
227+ return this;
228+ }
229+
152230 /**
153231 * Returns the literal's characters with its escapes resolved: a doubled quote character and,
154- * depending on {@link #getEscaping()}, backslash escape sequences. PostgreSQL octal and
155- * hexadecimal escapes denote bytes, which are decoded as UTF-8. Dollar-quoted bodies are
232+ * depending on {@link #getEscaping()}, backslash or Unicode escape sequences. PostgreSQL octal
233+ * and hexadecimal escapes denote bytes, which are decoded as UTF-8. Dollar-quoted bodies are
156234 * returned unchanged.
235+ *
236+ * @throws IllegalArgumentException if a {@link Escaping#POSTGRESQL_UNICODE_ESCAPE} value has an
237+ * escape that PostgreSQL rejects; the parser rejects such literals
157238 */
158239 public String getNotExcapedValue() {
159240 if (quoteStr != null && quoteStr.startsWith("$")) {
160241 return value;
161242 }
162243 char quote = "\"".equals(quoteStr) ? '"' : '\'';
244+ if (escaping == Escaping.POSTGRESQL_UNICODE_ESCAPE) {
245+ return unescapeUnicode(value, quote,
246+ unicodeEscapeCharacter == null ? '\\' : unicodeEscapeCharacter);
247+ }
163248 Unescaped result = new Unescaped(value.length());
164249 int i = 0;
165250 while (i < value.length()) {
@@ -270,6 +355,82 @@ private static int appendNumber(Unescaped result, String text, int start, int ra
270355 return end;
271356 }
272357
358+ /**
359+ * Resolves PostgreSQL Unicode escapes the way the server does: {@code escape} followed by four
360+ * hexadecimal digits, or by {@code +} and six, names a code point, and a UTF-16 surrogate pair
361+ * must be written as two consecutive escapes. A doubled escape or quote character stands for
362+ * itself.
363+ */
364+ private static String unescapeUnicode(String text, char quote, char escape) {
365+ checkUnicodeEscapeCharacter(escape);
366+ UnicodeUnescaped result = new UnicodeUnescaped(text.length());
367+ int i = 0;
368+ while (i < text.length()) {
369+ char c = text.charAt(i);
370+ boolean doubled = i + 1 < text.length() && text.charAt(i + 1) == c;
371+ if (c == escape && !doubled) {
372+ i = appendUnicodeEscape(result, text, i, escape);
373+ } else {
374+ result.append(c, i);
375+ i += doubled && (c == escape || c == quote) ? 2 : 1;
376+ }
377+ }
378+ return result.finish(text.length());
379+ }
380+
381+ private static void checkUnicodeEscapeCharacter(char escape) {
382+ if (escape > 0x7F || isHexDigit(escape) || "+'\" \t\n\r\f\u000B".indexOf(escape) >= 0) {
383+ throw new IllegalArgumentException("invalid Unicode escape character '" + escape + "'");
384+ }
385+ }
386+
387+ /**
388+ * Appends the code point of the escape at {@code position}, {@code escape} followed by four
389+ * hexadecimal digits or by {@code +} and six, and returns the next index.
390+ */
391+ private static int appendUnicodeEscape(UnicodeUnescaped result, String text, int position,
392+ char escape) {
393+ boolean plus = position + 1 < text.length() && text.charAt(position + 1) == '+';
394+ int start = plus ? position + 2 : position + 1;
395+ int end = start + (plus ? 6 : 4);
396+ int codePoint = parseHex(text, start, end);
397+ if (codePoint < 0) {
398+ throw new IllegalArgumentException("invalid Unicode escape at position " + position
399+ + ": Unicode escapes must be " + escape + "XXXX or " + escape + "+XXXXXX");
400+ }
401+ if (codePoint == 0 || codePoint > Character.MAX_CODE_POINT) {
402+ throw new IllegalArgumentException(
403+ "invalid Unicode escape value at position " + position);
404+ }
405+ result.appendCodePoint(codePoint, position);
406+ return end;
407+ }
408+
409+ private static IllegalArgumentException invalidSurrogatePair(int position) {
410+ return new IllegalArgumentException(
411+ "invalid Unicode surrogate pair at position " + position);
412+ }
413+
414+ private static boolean isHexDigit(char c) {
415+ return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F';
416+ }
417+
418+ /** Returns the ASCII hexadecimal number spelled by text[start, end), or -1. */
419+ private static int parseHex(String text, int start, int end) {
420+ if (end > text.length()) {
421+ return -1;
422+ }
423+ int number = 0;
424+ for (int i = start; i < end; i++) {
425+ char c = text.charAt(i);
426+ if (!isHexDigit(c)) {
427+ return -1;
428+ }
429+ number = number * 16 + Character.digit(c, 16);
430+ }
431+ return number;
432+ }
433+
273434 /** Collects unescaped characters; consecutive escaped bytes are decoded as UTF-8. */
274435 private static final class Unescaped {
275436 private final StringBuilder chars;
@@ -307,14 +468,65 @@ public String toString() {
307468 }
308469 }
309470
471+ /**
472+ * Collects resolved Unicode escapes. A UTF-16 surrogate pair must be written as two consecutive
473+ * escapes, as PostgreSQL requires.
474+ */
475+ private static final class UnicodeUnescaped {
476+ private final StringBuilder chars;
477+ private char highSurrogate;
478+
479+ UnicodeUnescaped(int capacity) {
480+ chars = new StringBuilder(capacity);
481+ }
482+
483+ void append(char c, int position) {
484+ requireNoPendingSurrogate(position);
485+ chars.append(c);
486+ }
487+
488+ void appendCodePoint(int codePoint, int position) {
489+ if (codePoint >= Character.MIN_LOW_SURROGATE
490+ && codePoint <= Character.MAX_LOW_SURROGATE) {
491+ if (highSurrogate == 0) {
492+ throw invalidSurrogatePair(position);
493+ }
494+ chars.appendCodePoint(Character.toCodePoint(highSurrogate, (char) codePoint));
495+ highSurrogate = 0;
496+ return;
497+ }
498+ requireNoPendingSurrogate(position);
499+ if (codePoint >= Character.MIN_HIGH_SURROGATE
500+ && codePoint <= Character.MAX_HIGH_SURROGATE) {
501+ highSurrogate = (char) codePoint;
502+ } else {
503+ chars.appendCodePoint(codePoint);
504+ }
505+ }
506+
507+ String finish(int position) {
508+ requireNoPendingSurrogate(position);
509+ return chars.toString();
510+ }
511+
512+ private void requireNoPendingSurrogate(int position) {
513+ if (highSurrogate != 0) {
514+ throw invalidSurrogatePair(position);
515+ }
516+ }
517+ }
518+
310519 @Override
311520 public <T, S> T accept(ExpressionVisitor<T> expressionVisitor, S context) {
312521 return expressionVisitor.visit(this, context);
313522 }
314523
315524 @Override
316525 public String toString() {
317- return (prefix != null ? prefix : "") + quoteStr + value + quoteStr;
526+ String unicodeEscape = unicodeEscapeCharacter != null
527+ ? " UESCAPE '" + unicodeEscapeCharacter + "'"
528+ : "";
529+ return (prefix != null ? prefix : "") + quoteStr + value + quoteStr + unicodeEscape;
318530 }
319531
320532 public StringValue withPrefix(String prefix) {
0 commit comments