Datasets:
Tasks:
Text Generation
Formats:
parquet
Sub-tasks:
language-modeling
Languages:
English
Size:
< 1K
License:
File size: 34,344 Bytes
92c3b9e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 | diff --git a/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java b/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
index 2ad08d6..1ebbe21 100644
--- a/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
+++ b/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
@@ -677,6 +677,14 @@ public class SQLUtils {
return parseStatements(sql, DbType.of(dbType), features);
}
+ /**
+ * Reads a whole script; statements the strict parser cannot read come back as
+ * {@link com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement} in place, the rest as today.
+ */
+ public static List<SQLStatement> parseStatementsLenient(String sql, DbType dbType) {
+ return new com.alibaba.druid.sql.parser.LenientScriptParser(sql, dbType).parse();
+ }
+
public static List<SQLStatement> parseStatements(String sql, DbType dbType, SQLParserFeature... features) {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, features);
List<SQLStatement> stmtList = new ArrayList<SQLStatement>();
diff --git a/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java b/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java
new file mode 100644
index 0000000..336039b
--- /dev/null
+++ b/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java
@@ -0,0 +1,69 @@
+package com.alibaba.druid.sql.ast.statement;
+
+import com.alibaba.druid.DbType;
+import com.alibaba.druid.sql.ast.SQLStatementImpl;
+import com.alibaba.druid.sql.visitor.SQLASTVisitor;
+import com.alibaba.druid.sql.visitor.VisitorFeature;
+
+/**
+ * A statement the strict parser could not read, kept as its source text by the lenient script read.
+ */
+public class SQLUnparsedStatement extends SQLStatementImpl {
+ private final String sql;
+ private final String error;
+ private final int line;
+ private final int column;
+
+ public SQLUnparsedStatement(DbType dbType, String sql, String error, int line, int column) {
+ super(dbType);
+ this.sql = sql;
+ this.error = error;
+ this.line = line;
+ this.column = column;
+ }
+
+ /** The statement's source text, exactly as written, without its delimiter. */
+ public String getSql() {
+ return sql;
+ }
+
+ /** The strict parser's message for this text, positions counted from the start of the whole script. */
+ public String getError() {
+ return error;
+ }
+
+ public int getLine() {
+ return line;
+ }
+
+ public int getColumn() {
+ return column;
+ }
+
+ @Override
+ protected void accept0(SQLASTVisitor v) {
+ // nothing to visit
+ }
+
+ @Override
+ public void output(StringBuilder buf) {
+ buf.append(sql);
+ }
+
+ @Override
+ public String toString() {
+ return sql;
+ }
+
+ @Override
+ public String toString(VisitorFeature... features) {
+ return sql;
+ }
+
+ @Override
+ public SQLUnparsedStatement clone() {
+ SQLUnparsedStatement x = new SQLUnparsedStatement(dbType, sql, error, line, column);
+ x.setAfterSemi(afterSemi);
+ return x;
+ }
+}
diff --git a/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java b/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java
new file mode 100644
index 0000000..9fba816
--- /dev/null
+++ b/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java
@@ -0,0 +1,462 @@
+package com.alibaba.druid.sql.parser;
+
+import com.alibaba.druid.DbType;
+import com.alibaba.druid.sql.ast.SQLStatement;
+import com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Reads a whole script in one lexer pass. Every statement the strict parser reads is returned as today; every
+ * statement it cannot read is returned as {@link SQLUnparsedStatement} holding its exact source text and the strict
+ * parser's message for that text, with positions moved to the script. The extent of an unparsed statement is found
+ * by scanning its tokens with the dialect's block structure (a compound statement is one statement) up to the
+ * semicolon that ends it at the top level; a statement whose lexer never recovers runs to the end of the input.
+ */
+public class LenientScriptParser {
+ /** the script as handed in */
+ private final String sql;
+ /** the text the lexer reads: the parser factory rewrites CRLF to LF, so lexer positions refer to this one */
+ private final String text;
+ private final DbType dbType;
+ private final SQLStatementParser parser;
+ private final Lexer lexer;
+
+ public LenientScriptParser(String sql, DbType dbType) {
+ this.sql = sql;
+ this.dbType = dbType == null ? DbType.other : dbType;
+ this.parser = SQLParserUtils.createSQLStatementParser(sql, this.dbType, new SQLParserFeature[0]);
+ this.lexer = parser.getLexer();
+ this.text = lexer.text;
+ }
+
+ /** original offset of a normalized offset; end = true maps the exclusive end of a slice */
+ private int orig(int idx, boolean end) {
+ if (text.length() == sql.length()) {
+ return idx;
+ }
+ if (end) {
+ if (idx <= 0) {
+ return 0;
+ }
+ return orig(idx - 1, false) + 1;
+ }
+ // walk both strings: every "\r\n" of the original is one "\n" of the text
+ int j = 0;
+ for (int i = 0; i < idx && j < sql.length(); i++) {
+ if (sql.charAt(j) == '\r' && j + 1 < sql.length() && sql.charAt(j + 1) == '\n' && text.charAt(i) == '\n') {
+ j++;
+ }
+ j++;
+ }
+ if (idx < text.length() && j < sql.length() && sql.charAt(j) == '\r' && j + 1 < sql.length() && sql.charAt(j + 1) == '\n' && text.charAt(idx) == '\n') {
+ j++;
+ }
+ return j;
+ }
+
+ public List<SQLStatement> parse() {
+ List<SQLStatement> out = new ArrayList<SQLStatement>();
+ while (true) {
+ // delimiters and comment tokens between statements, handled as the dialect's own loop handles them: the
+ // base loop hands the comments after a delimiter to the previous statement, Oracle's loop leaves them for
+ // the next one
+ try {
+ while (true) {
+ while (lexer.token() == Token.MULTI_LINE_COMMENT || lexer.token() == Token.LINE_COMMENT) {
+ lexer.nextToken();
+ }
+ if (lexer.token() != Token.SEMI) {
+ break;
+ }
+ char ch = lexer.ch;
+ lexer.nextToken();
+ if (!out.isEmpty()) {
+ SQLStatement last = out.get(out.size() - 1);
+ last.setAfterSemi(true);
+ if (!isOracle() && lexer.isKeepComments()) {
+ if (ch == '\n' && lexer.getComments() != null && !lexer.getComments().isEmpty()
+ && !(last instanceof com.alibaba.druid.sql.ast.statement.SQLSetStatement)) {
+ lexer.getComments().add(0, new String("\n"));
+ }
+ last.addAfterComment(lexer.readAndResetComments());
+ }
+ }
+ }
+ } catch (RuntimeException e) {
+ // the lexer failed on the first token after a delimiter: that statement runs to the end of the input
+ addUnparsed(out, firstTokenStart(lexer.mark), text.length());
+ return out;
+ }
+ if (lexer.token() == Token.EOF) {
+ break;
+ }
+ Lexer.SavePoint sp = lexer.mark();
+ int before = out.size();
+ boolean ok;
+ try {
+ // one statement through the dialect's own loop, which also consumes delimiters and comments as today
+ parser.parseStatementList(out, before + 1, null);
+ // what the strict loop accepted as one statement is one statement; only delimiters and comments
+ // followed by the end of the input add nothing
+ ok = out.size() == before + 1 || (out.size() == before && lexer.token() == Token.EOF);
+ } catch (RuntimeException e) {
+ ok = false;
+ }
+ if (ok) {
+ if (out.size() == before) {
+ break;
+ }
+ continue;
+ }
+ while (out.size() > before) {
+ out.remove(out.size() - 1);
+ }
+ lexer.reset(sp);
+ int[] se = skipStatement();
+ addUnparsed(out, se[0], se[1]);
+ if (se[1] >= text.length()) {
+ return out;
+ }
+ // the lexer stands on the delimiter; the next round's strict loop consumes it as today
+ }
+ return out;
+ }
+
+ /**
+ * The lexer's startPos for a token that follows kept comments points at the first comment; the statement's text
+ * begins at its first token, so step over whitespace and comments from there (offsets in the lexer's text).
+ */
+ private int firstTokenStart(int from) {
+ int i = from < 0 ? 0 : from;
+ int n = text.length();
+ while (i < n) {
+ char c = text.charAt(i);
+ if (Character.isWhitespace(c)) {
+ i++;
+ } else if (c == '-' && i + 1 < n && text.charAt(i + 1) == '-') {
+ while (i < n && text.charAt(i) != '\n') {
+ i++;
+ }
+ } else if (c == '#' && isMySql()) {
+ while (i < n && text.charAt(i) != '\n') {
+ i++;
+ }
+ } else if (c == '/' && i + 1 < n && text.charAt(i + 1) == '*') {
+ int close = text.indexOf("*/", i + 2);
+ if (close < 0) {
+ return i;
+ }
+ i = close + 2;
+ } else {
+ break;
+ }
+ }
+ return i;
+ }
+
+ /** start and end are offsets in the lexer's text; the item keeps the original characters */
+ private void addUnparsed(List<SQLStatement> out, int start, int end) {
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > text.length()) {
+ end = text.length();
+ }
+ if (end < start) {
+ end = start;
+ }
+ int oStart = orig(start, false);
+ int oEnd = end >= text.length() ? sql.length() : orig(end, true);
+ if (oEnd < oStart) {
+ oEnd = oStart;
+ }
+ start = oStart;
+ String item = sql.substring(oStart, oEnd);
+ String msg = strictMessage(item);
+ int line = 1, col = 1;
+ for (int i = 0; i < start; i++) {
+ if (sql.charAt(i) == '\n') {
+ line++;
+ col = 1;
+ } else {
+ col++;
+ }
+ }
+ String moved = move(msg, start, line, col);
+ int[] lc = lineCol(moved);
+ SQLUnparsedStatement u = new SQLUnparsedStatement(dbType, item, moved, lc[0], lc[1]);
+ out.add(u);
+ }
+
+ /** The strict parser's message for the text on its own. */
+ private String strictMessage(String text) {
+ try {
+ SQLStatementParser p = SQLParserUtils.createSQLStatementParser(text, dbType, new SQLParserFeature[0]);
+ List<SQLStatement> l = new ArrayList<SQLStatement>();
+ p.parseStatementList(l, -1, null);
+ if (p.getLexer().token() != Token.EOF) {
+ return "syntax error : " + p.getLexer().info();
+ }
+ return "syntax error";
+ } catch (RuntimeException e) {
+ return e.getMessage() == null ? e.toString() : e.getMessage();
+ }
+ }
+
+ // ------------------------------------------------------------------ extent
+
+ private boolean isMySql() {
+ return dbType == DbType.mysql || dbType == DbType.mariadb || dbType == DbType.tidb || dbType == DbType.oceanbase
+ || dbType == DbType.polardbx || dbType == DbType.drds || dbType == DbType.ads;
+ }
+
+ private boolean isOracle() {
+ return dbType == DbType.oracle || dbType == DbType.oceanbase_oracle || dbType == DbType.polardb2;
+ }
+
+ private boolean isSqlServer() {
+ return dbType == DbType.sqlserver || dbType == DbType.jtds;
+ }
+
+ private boolean isPg() {
+ return dbType == DbType.postgresql || dbType == DbType.edb || dbType == DbType.greenplum || dbType == DbType.gaussdb
+ || dbType == DbType.hologres || dbType == DbType.redshift;
+ }
+
+ /**
+ * From the first token of a statement, scan to the delimiter ending it as a top level statement. Returns the end
+ * offset (exclusive) of its last token and leaves the lexer on that delimiter (or EOF). When the lexer cannot read
+ * on, the statement runs to the end of the input.
+ */
+ private int[] skipStatement() {
+ // leading delimiters and comment tokens belong to no statement
+ try {
+ while (lexer.token() == Token.SEMI || lexer.token() == Token.MULTI_LINE_COMMENT || lexer.token() == Token.LINE_COMMENT) {
+ lexer.nextToken();
+ }
+ } catch (RuntimeException e) {
+ // the lexer failed on the first token: that statement runs to the end of the input
+ return new int[] {firstTokenStart(lexer.mark), text.length()};
+ }
+ int start = firstTokenStart(lexer.startPos);
+ if (lexer.token() == Token.EOF) {
+ return new int[] {start, start};
+ }
+ int depth = 0;
+ // per depth: whether the next BEGIN at this level is the body of an already opened block (DECLARE, IS/AS)
+ boolean[] absorb = new boolean[256];
+ int end = lexer.pos();
+ boolean stmtStart = true;
+ boolean afterEnd = false;
+ boolean routinePending = false;
+ Token prev = null;
+ while (true) {
+ Token t = lexer.token();
+ if (t == Token.EOF) {
+ return new int[] {start, end};
+ }
+ if (t == Token.ERROR) {
+ // a literal, quoted name or comment the lexer could not close runs to the end of the input;
+ // any other unreadable character is just a token of the statement
+ char c = lexer.startPos < text.length() ? text.charAt(lexer.startPos) : ' ';
+ if (lexer.pos() >= text.length() || c == '\'' || c == '"' || c == '`' || c == '[' || c == '/') {
+ return new int[] {start, text.length()};
+ }
+ }
+ if (t == Token.SEMI && depth == 0) {
+ if (isSqlServer()) {
+ // IF cond stmt; ELSE stmt; is one statement
+ Lexer.SavePoint sp = lexer.mark();
+ try {
+ lexer.nextToken();
+ } catch (RuntimeException e) {
+ return new int[] {start, text.length()};
+ }
+ if (lexer.token() == Token.ELSE) {
+ prev = Token.SEMI;
+ stmtStart = true;
+ // fall through to treat ELSE as an ordinary token
+ } else {
+ lexer.reset(sp);
+ return new int[] {start, end};
+ }
+ } else {
+ return new int[] {start, end};
+ }
+ }
+ t = lexer.token();
+ boolean startHere = stmtStart;
+ boolean opener = false;
+ boolean closerKeyword = false;
+ if (afterEnd) {
+ if (t == Token.IF || t == Token.LOOP || t == Token.CASE || t == Token.WHILE || t == Token.REPEAT
+ || lexer.identifierEquals("TRY") || lexer.identifierEquals("CATCH")) {
+ closerKeyword = true;
+ }
+ afterEnd = false;
+ }
+ if (!closerKeyword) {
+ if (t == Token.BEGIN) {
+ opener = beginOpensBlock();
+ if (opener && depth > 0 && absorb[depth]) {
+ opener = false;
+ absorb[depth] = false;
+ }
+ } else if (t == Token.CASE || t == Token.LOOP) {
+ opener = true;
+ } else if (t == Token.IF) {
+ opener = startHere && !isSqlServer();
+ } else if (t == Token.WHILE || t == Token.REPEAT) {
+ opener = startHere && isMySql();
+ } else if (t == Token.DECLARE) {
+ if (startHere && (isOracle() || isPg())) {
+ opener = true;
+ if (depth + 1 < absorb.length) {
+ absorb[depth + 1] = true;
+ }
+ }
+ } else if (t == Token.PROCEDURE || t == Token.FUNCTION || lexer.identifierEquals("PACKAGE")) {
+ if (isOracle() && (startHere || prev == Token.CREATE || prev == Token.REPLACE)) {
+ routinePending = true;
+ }
+ } else if ((t == Token.IS || t == Token.AS) && routinePending) {
+ routinePending = false;
+ opener = true;
+ if (depth + 1 < absorb.length) {
+ absorb[depth + 1] = true;
+ }
+ } else if (t == Token.END) {
+ if (depth > 0) {
+ absorb[depth] = false;
+ depth--;
+ }
+ afterEnd = true;
+ }
+ }
+ if (opener) {
+ depth++;
+ if (t == Token.BEGIN || t == Token.LOOP || t == Token.CASE || t == Token.IF || t == Token.WHILE || t == Token.REPEAT) {
+ // a fresh block: nothing pending to absorb at this level unless set above
+ if (t != Token.BEGIN && depth < absorb.length && !(t == Token.DECLARE)) {
+ absorb[depth] = absorb[depth] && false;
+ }
+ }
+ }
+ stmtStart = t == Token.SEMI || t == Token.BEGIN || t == Token.THEN || t == Token.ELSE || t == Token.DO
+ || t == Token.LOOP || t == Token.EXCEPTION || t == Token.ELSEIF
+ || (t == Token.VARIANT && lexer.stringVal() != null && lexer.stringVal().startsWith("$"))
+ || (t == Token.VARIANT && ":".equals(lexer.stringVal()))
+ || (t == Token.IS || t == Token.AS) && opener
+ || t == Token.GTGT;
+ prev = t;
+ end = lexer.pos();
+ try {
+ lexer.nextToken();
+ } catch (RuntimeException e) {
+ return new int[] {start, text.length()};
+ }
+ }
+ }
+
+ /** BEGIN opens a block unless the dialect reads it as a transaction command. Consumes nothing (peeks and resets). */
+ private boolean beginOpensBlock() {
+ if (isOracle()) {
+ return true;
+ }
+ Lexer.SavePoint sp = lexer.mark();
+ boolean block;
+ try {
+ lexer.nextToken();
+ Token n = lexer.token();
+ if (isMySql()) {
+ block = !(n == Token.SEMI || n == Token.EOF || n == Token.IDENTIFIER);
+ } else if (isSqlServer()) {
+ block = !(lexer.identifierEquals("TRANSACTION") || lexer.identifierEquals("TRAN") || lexer.identifierEquals("DISTRIBUTED"));
+ } else {
+ block = !(n == Token.SEMI || n == Token.EOF || lexer.identifierEquals("WORK") || lexer.identifierEquals("TRANSACTION")
+ || lexer.identifierEquals("ISOLATION") || lexer.identifierEquals("READ") || lexer.identifierEquals("DEFERRABLE")
+ || lexer.identifierEquals("NOT"));
+ }
+ } catch (RuntimeException e) {
+ block = true;
+ }
+ lexer.reset(sp);
+ return block;
+ }
+
+ // ------------------------------------------------------------------ positions
+
+ /** Rewrites every "pos N, line L, column C" in a message from the statement's frame to the script's. */
+ static String move(String m, int start, int sLine, int sCol) {
+ if (m == null) {
+ return null;
+ }
+ StringBuilder sb = new StringBuilder();
+ int i = 0;
+ while (true) {
+ int p = m.indexOf("pos ", i);
+ if (p < 0) {
+ sb.append(m.substring(i));
+ break;
+ }
+ int pe = p + 4;
+ while (pe < m.length() && Character.isDigit(m.charAt(pe))) {
+ pe++;
+ }
+ if (pe == p + 4 || !m.startsWith(", line ", pe)) {
+ sb.append(m, i, pe);
+ i = pe;
+ continue;
+ }
+ int le = pe + 7;
+ while (le < m.length() && Character.isDigit(m.charAt(le))) {
+ le++;
+ }
+ if (le == pe + 7 || !m.startsWith(", column ", le)) {
+ sb.append(m, i, le);
+ i = le;
+ continue;
+ }
+ int ce = le + 9;
+ while (ce < m.length() && Character.isDigit(m.charAt(ce))) {
+ ce++;
+ }
+ if (ce == le + 9) {
+ sb.append(m, i, ce);
+ i = ce;
+ continue;
+ }
+ int pos = Integer.parseInt(m.substring(p + 4, pe));
+ int line = Integer.parseInt(m.substring(pe + 7, le));
+ int col = Integer.parseInt(m.substring(le + 9, ce));
+ sb.append(m, i, p).append("pos ").append(pos + start).append(", line ").append(line + sLine - 1)
+ .append(", column ").append(line == 1 ? col + sCol - 1 : col);
+ i = ce;
+ }
+ return sb.toString();
+ }
+
+ static int[] lineCol(String m) {
+ if (m == null) {
+ return new int[] {-1, -1};
+ }
+ int li = m.indexOf(", line ");
+ if (li < 0) {
+ return new int[] {-1, -1};
+ }
+ int l = num(m, li + 7);
+ int ci = m.indexOf(", column ", li);
+ int c = ci < 0 ? -1 : num(m, ci + 9);
+ return new int[] {l, c};
+ }
+
+ static int num(String m, int j) {
+ int k = j;
+ while (k < m.length() && Character.isDigit(m.charAt(k))) {
+ k++;
+ }
+ return k == j ? -1 : Integer.parseInt(m.substring(j, k));
+ }
+}
diff --git a/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java b/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java
new file mode 100644
index 0000000..9bdc701
--- /dev/null
+++ b/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java
@@ -0,0 +1,227 @@
+package com.alibaba.druid.bvt.sql;
+
+import com.alibaba.druid.DbType;
+import com.alibaba.druid.sql.SQLUtils;
+import com.alibaba.druid.sql.ast.SQLStatement;
+import com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The lenient whole-script read: SQLUtils.parseStatementsLenient returns what the strict call reads as today and the
+ * rest as SQLUnparsedStatement carrying the statement's exact text and the strict message for that text on its own,
+ * with pos, line and column counted from the script start.
+ */
+public class LenientScriptReadTest {
+ private static final Pattern POS = Pattern.compile("pos (\\d+), line (\\d+), column (\\d+)");
+
+ private static List<SQLUnparsedStatement> unparsedOf(List<SQLStatement> list) {
+ List<SQLUnparsedStatement> out = new ArrayList<SQLUnparsedStatement>();
+ for (SQLStatement s : list) {
+ if (s instanceof SQLUnparsedStatement) {
+ out.add((SQLUnparsedStatement) s);
+ }
+ }
+ return out;
+ }
+
+ /** the message the strict call gives for a text on its own */
+ private static String strictMessage(String sql, DbType dbType) {
+ try {
+ SQLUtils.parseStatements(sql, dbType);
+ } catch (Exception e) {
+ return e.getMessage();
+ }
+ fail("the text should not parse on its own: " + sql);
+ return null;
+ }
+
+ /** the same message with pos, line and column counted from the script start, for a statement starting at (offset, line, column) */
+ private static String counted(String standalone, int offset, int line, int column) {
+ Matcher m = POS.matcher(standalone);
+ StringBuffer sb = new StringBuffer();
+ while (m.find()) {
+ int p = Integer.parseInt(m.group(1)), l = Integer.parseInt(m.group(2)), c = Integer.parseInt(m.group(3));
+ m.appendReplacement(sb, "pos " + (p + offset) + ", line " + (l + line - 1) + ", column " + (l == 1 ? c + column - 1 : c));
+ }
+ m.appendTail(sb);
+ return sb.toString();
+ }
+
+ private static int lineOf(String error) {
+ Matcher m = POS.matcher(error);
+ assertTrue(m.find(), error);
+ return Integer.parseInt(m.group(2));
+ }
+
+ private static int columnOf(String error) {
+ Matcher m = POS.matcher(error);
+ assertTrue(m.find(), error);
+ return Integer.parseInt(m.group(3));
+ }
+
+ @Test
+ public void allGoodComesBackAsStrict() {
+ String sql = "select id from t where x = 1; insert into t (a) values (2); update t set a = 3;";
+ List<SQLStatement> strict = SQLUtils.parseStatements(sql, DbType.mysql);
+ List<SQLStatement> lenient = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ assertEquals(strict.size(), lenient.size());
+ for (int i = 0; i < strict.size(); ++i) {
+ assertEquals(strict.get(i).toString(), lenient.get(i).toString());
+ }
+ assertTrue(unparsedOf(lenient).isEmpty());
+ }
+
+ @Test
+ public void badSimpleStatementBetweenGoodOnes() {
+ String bad = "select a from where a = 1";
+ String sql = "select 1; " + bad + "; select 3;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ assertEquals(3, list.size());
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
+ assertEquals(bad, u.getSql());
+ assertEquals(bad, u.toString());
+ String standalone = strictMessage(bad, DbType.mysql);
+ assertEquals(counted(standalone, 10, 1, 11), u.getError());
+ assertEquals(lineOf(u.getError()), u.getLine());
+ assertEquals(columnOf(u.getError()), u.getColumn());
+ }
+
+ @Test
+ public void errorLineCountedFromScriptStart() {
+ String sql = "select 1;\nselect * from t where a ==== 1;\nselect 3;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ assertEquals(3, list.size());
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
+ assertEquals("select * from t where a ==== 1", u.getSql());
+ assertEquals("ERROR. pos 38, line 2, column 27, token ==", u.getError());
+ assertEquals(2, u.getLine());
+ assertEquals(27, u.getColumn());
+ }
+
+ @Test
+ public void whatFollowsParsesAsTheScriptWithoutIt() {
+ String script = "select 1; nonsense here; select 2 from t; create table x (id bigint);";
+ String without = "select 1; select 2 from t; create table x (id bigint);";
+ List<SQLStatement> lenient = SQLUtils.parseStatementsLenient(script, DbType.mysql);
+ List<SQLStatement> strict = SQLUtils.parseStatements(without, DbType.mysql);
+ assertEquals(4, lenient.size());
+ assertTrue(lenient.get(1) instanceof SQLUnparsedStatement);
+ assertEquals(strict.get(0).toString(), lenient.get(0).toString());
+ assertEquals(strict.get(1).toString(), lenient.get(2).toString());
+ assertEquals(strict.get(2).toString(), lenient.get(3).toString());
+ }
+
+ @Test
+ public void compoundStatementIsOneStatement() {
+ String sql = "create procedure p() begin if x > 0 then begin select bad from; end; end if; end; select 7;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ assertEquals(2, list.size());
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(0);
+ assertEquals("create procedure p() begin if x > 0 then begin select bad from; end; end if; end", u.getSql());
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
+ }
+
+ @Test
+ public void compoundLoopsAreOneStatement() {
+ String sql = "create procedure p() begin while i < 10 do set i = i + + ; end while; end; select 7;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ assertEquals(2, list.size());
+ assertEquals("create procedure p() begin while i < 10 do set i = i + + ; end while; end",
+ ((SQLUnparsedStatement) list.get(0)).getSql());
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
+ }
+
+ @Test
+ public void oracleDeclareSectionBelongsToTheBlock() {
+ String sql = "begin null; end;\ndeclare x number; begin x := ; end;\nselect 1 from dual;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.oracle);
+ assertEquals(3, list.size());
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
+ assertEquals("declare x number; begin x := ; end", u.getSql());
+ assertEquals(2, u.getLine());
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
+ }
+
+ @Test
+ public void sqlServerIfElseBranchesAreOneStatement() {
+ String sql = "if 1 = 1 select bad from; else select 2;\nselect 3;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.sqlserver);
+ assertEquals(2, list.size());
+ assertEquals("if 1 = 1 select bad from; else select 2", ((SQLUnparsedStatement) list.get(0)).getSql());
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
+ }
+
+ @Test
+ public void keywordsAsNamesFunctionsModifiersAndTransactionsOpenNothing() {
+ String sql = "begin; select 1; commit; select if(a, 1, 2) from t; select `end` from t; drop table if exists t2;"
+ + " delete from where a = 1; select 4;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ List<SQLUnparsedStatement> bad = unparsedOf(list);
+ assertEquals(1, bad.size());
+ assertEquals("delete from where a = 1", bad.get(0).getSql());
+ assertEquals(8, list.size());
+ assertFalse(list.get(7) instanceof SQLUnparsedStatement);
+ }
+
+ @Test
+ public void unclosedStringRunsToTheEndOfTheInput() {
+ String tail = "select 'abc; select 3;";
+ String sql = "select 1; " + tail;
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ assertEquals(2, list.size());
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
+ assertEquals(tail, u.getSql());
+ assertEquals(counted(strictMessage(tail, DbType.mysql), 10, 1, 11), u.getError());
+ }
+
+ @Test
+ public void textIsExactUnderCrlf() {
+ String bad = "select a from where a = 1";
+ String sql = "select 1;\r\n" + bad + ";\r\nselect 3;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ assertEquals(3, list.size());
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
+ assertEquals(bad, u.getSql());
+ assertEquals(2, u.getLine());
+ assertEquals(counted(strictMessage(bad, DbType.mysql), 11, 2, 1), u.getError());
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
+ }
+
+ @Test
+ public void commentAheadOfABadStatementIsNotPartOfItsText() {
+ String bad = "select a from where a = 1";
+ String sql = "select 1;\n-- note\n" + bad + ";\n/* block */ select 3;";
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
+ assertEquals(3, list.size());
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
+ assertEquals(bad, u.getSql());
+ assertEquals(3, u.getLine());
+ assertEquals(counted(strictMessage(bad, DbType.mysql), 18, 3, 1), u.getError());
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
+ }
+
+ @Test
+ public void strictEntryPointsUnchanged() {
+ try {
+ SQLUtils.parseStatements("select 1; select a from where a = 1; select 3;", DbType.mysql);
+ fail("the strict call must still fail on a bad statement");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("pos "), e.getMessage());
+ }
+ }
+}
|