From 9941105319626e297b35c27bda4566a885a5d0c7 Mon Sep 17 00:00:00 2001 From: jxnu-liguobin Date: Sat, 16 Dec 2023 17:20:41 +0800 Subject: [PATCH 1/5] feat: Support `FOR SHARE` --- .../sf/jsqlparser/parser/feature/Feature.java | 16 +++++ .../statement/select/PlainSelect.java | 60 +++++++++++++++---- .../util/deparser/SelectDeParser.java | 21 ++++++- .../util/validation/feature/MySqlVersion.java | 1 + .../validation/feature/PostgresqlVersion.java | 3 + .../validation/validator/SelectValidator.java | 8 ++- .../net/sf/jsqlparser/parser/JSqlParserCC.jjt | 10 +++- .../statement/select/SelectTest.java | 8 +++ .../validator/SelectValidatorTest.java | 56 ++++++++++++----- 9 files changed, 153 insertions(+), 30 deletions(-) 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 956d636b5..9b8502094 100644 --- a/src/main/java/net/sf/jsqlparser/parser/feature/Feature.java +++ b/src/main/java/net/sf/jsqlparser/parser/feature/Feature.java @@ -244,6 +244,22 @@ public enum Feature { * "FOR UPDATE" */ selectForUpdate, + + /** + * "FOR SHARE" + */ + selectForShare, + + /** + * "FOR KEY SHARE" + */ + selectForKeyShare, + + /** + * "NO KEY UPDATE" + */ + selectForNoKeyUpdate, + /** * "FOR UPDATE OF table" */ diff --git a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java index 5e322c52f..067175dd0 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java @@ -9,12 +9,7 @@ */ package net.sf.jsqlparser.statement.select; -import net.sf.jsqlparser.expression.Alias; -import net.sf.jsqlparser.expression.Expression; -import net.sf.jsqlparser.expression.OracleHierarchicalExpression; -import net.sf.jsqlparser.expression.OracleHint; -import net.sf.jsqlparser.expression.WindowDefinition; -import net.sf.jsqlparser.schema.Table; +import static java.util.stream.Collectors.joining; import java.util.ArrayList; import java.util.Arrays; @@ -23,8 +18,12 @@ import java.util.Iterator; import java.util.List; import java.util.Optional; - -import static java.util.stream.Collectors.joining; +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.OracleHierarchicalExpression; +import net.sf.jsqlparser.expression.OracleHint; +import net.sf.jsqlparser.expression.WindowDefinition; +import net.sf.jsqlparser.schema.Table; @SuppressWarnings({"PMD.CyclomaticComplexity"}) public class PlainSelect extends Select { @@ -47,6 +46,9 @@ public class PlainSelect extends Select { private OracleHierarchicalExpression oracleHierarchical = null; private OracleHint oracleHint = null; private boolean forUpdate = false; + private boolean forShare = false; + private boolean forNoKeyUpdate = false; + private boolean forKeyShare = false; private Table forUpdateTable = null; private boolean skipLocked; private Wait wait; @@ -486,8 +488,22 @@ public StringBuilder appendSelectBodyTo(StringBuilder builder) { if (emitChanges) { builder.append(" EMIT CHANGES"); } - if (isForUpdate()) { - builder.append(" FOR UPDATE"); + if (isForUpdate() || isForShare() || isForKeyShare() || isForNoKeyUpdate()) { + builder.append(" FOR "); + String type = null; + if (isForUpdate()) { + type = "UPDATE"; + } + if (isForShare()) { + type = "SHARE"; + } + if (isForKeyShare()) { + type = "KEY SHARE"; + } + if (isForNoKeyUpdate()) { + type = "NO KEY UPDATE"; + } + builder.append(type); if (forUpdateTable != null) { builder.append(" OF ").append(forUpdateTable); @@ -685,6 +701,30 @@ public PlainSelect addJoins(Collection joins) { return this.withJoins(collection); } + public boolean isForShare() { + return forShare; + } + + public void setForShare(boolean forShare) { + this.forShare = forShare; + } + + public boolean isForNoKeyUpdate() { + return forNoKeyUpdate; + } + + public void setForNoKeyUpdate(boolean forNoKeyUpdate) { + this.forNoKeyUpdate = forNoKeyUpdate; + } + + public boolean isForKeyShare() { + return forKeyShare; + } + + public void setForKeyShare(boolean forKeyShare) { + this.forKeyShare = forKeyShare; + } + public E getFromItem(Class type) { return type.cast(getFromItem()); } diff --git a/src/main/java/net/sf/jsqlparser/util/deparser/SelectDeParser.java b/src/main/java/net/sf/jsqlparser/util/deparser/SelectDeParser.java index 7c4c0e1fb..ee591351e 100644 --- a/src/main/java/net/sf/jsqlparser/util/deparser/SelectDeParser.java +++ b/src/main/java/net/sf/jsqlparser/util/deparser/SelectDeParser.java @@ -268,8 +268,25 @@ public void visit(PlainSelect plainSelect) { buffer.append(plainSelect.getWindowDefinitions().stream() .map(WindowDefinition::toString).collect(joining(", "))); } - if (plainSelect.isForUpdate()) { - buffer.append(" FOR UPDATE"); + if (plainSelect.isForUpdate() || plainSelect.isForShare() || plainSelect.isForNoKeyUpdate() + || plainSelect.isForKeyShare()) { + buffer.append(" FOR "); + + String type = null; + if (plainSelect.isForUpdate()) { + type = "UPDATE"; + } + if (plainSelect.isForShare()) { + type = "SHARE"; + } + if (plainSelect.isForKeyShare()) { + type = "KEY SHARE"; + } + if (plainSelect.isForNoKeyUpdate()) { + type = "NO KEY UPDATE"; + } + buffer.append(type); + if (plainSelect.getForUpdateTable() != null) { buffer.append(" OF ").append(plainSelect.getForUpdateTable()); } diff --git a/src/main/java/net/sf/jsqlparser/util/validation/feature/MySqlVersion.java b/src/main/java/net/sf/jsqlparser/util/validation/feature/MySqlVersion.java index 3486261ed..a2397f9c5 100644 --- a/src/main/java/net/sf/jsqlparser/util/validation/feature/MySqlVersion.java +++ b/src/main/java/net/sf/jsqlparser/util/validation/feature/MySqlVersion.java @@ -38,6 +38,7 @@ public enum MySqlVersion implements Version { Feature.selectForUpdateOfTable, Feature.selectForUpdateNoWait, Feature.selectForUpdateSkipLocked, + Feature.selectForShare, Feature.distinct, Feature.setOperation, diff --git a/src/main/java/net/sf/jsqlparser/util/validation/feature/PostgresqlVersion.java b/src/main/java/net/sf/jsqlparser/util/validation/feature/PostgresqlVersion.java index 21cec80d2..08bf3bf1a 100644 --- a/src/main/java/net/sf/jsqlparser/util/validation/feature/PostgresqlVersion.java +++ b/src/main/java/net/sf/jsqlparser/util/validation/feature/PostgresqlVersion.java @@ -73,6 +73,9 @@ public enum PostgresqlVersion implements Version { Feature.orderBy, Feature.orderByNullOrdering, + Feature.selectForNoKeyUpdate, + Feature.selectForKeyShare, + Feature.selectForShare, Feature.selectForUpdate, Feature.selectForUpdateOfTable, Feature.selectForUpdateNoWait, diff --git a/src/main/java/net/sf/jsqlparser/util/validation/validator/SelectValidator.java b/src/main/java/net/sf/jsqlparser/util/validation/validator/SelectValidator.java index 3cba4a988..4ca4275c6 100644 --- a/src/main/java/net/sf/jsqlparser/util/validation/validator/SelectValidator.java +++ b/src/main/java/net/sf/jsqlparser/util/validation/validator/SelectValidator.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.util.validation.validator; import java.util.List; + import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.MySQLIndexHint; import net.sf.jsqlparser.expression.SQLServerHints; @@ -85,8 +86,13 @@ public void visit(PlainSelect plainSelect) { isNotEmpty(plainSelect.getOrderByElements()) && plainSelect.isOracleSiblings(), Feature.oracleOrderBySiblings); - if (plainSelect.isForUpdate()) { + if (plainSelect.isForUpdate() || plainSelect.isForKeyShare() + || plainSelect.isForNoKeyUpdate() || plainSelect.isForShare()) { validateFeature(c, Feature.selectForUpdate); + validateFeature(c, plainSelect.isForKeyShare(), Feature.selectForKeyShare); + validateFeature(c, plainSelect.isForNoKeyUpdate(), Feature.selectForNoKeyUpdate); + validateFeature(c, plainSelect.isForShare(), Feature.selectForShare); + validateOptionalFeature(c, plainSelect.getForUpdateTable(), Feature.selectForUpdateOfTable); validateOptionalFeature(c, plainSelect.getWait(), Feature.selectForUpdateWait); diff --git a/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt b/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt index 547324944..f84598902 100644 --- a/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt +++ b/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt @@ -400,6 +400,7 @@ TOKEN: /* SQL Keywords. prefixed with K_ to avoid name clashes */ | | | +| | | | @@ -1801,7 +1802,7 @@ String RelObjectNameWithoutValue() : { Token tk = null; } { ( tk= | tk= | tk= | tk= | tk= | tk= | tk= - | tk="ACTION" | tk="ACTIVE" | tk="ADD" | tk="ADVANCE" | tk="ADVISE" | tk="AGAINST" | tk="ALGORITHM" | tk="ALTER" | tk="ANALYZE" | tk="APPLY" | tk="ARCHIVE" | tk="ARRAY" | tk="ASC" | tk="AT" | tk="AUTHORIZATION" | tk="AUTO" | tk="BEGIN" | tk="BERNOULLI" | tk="BINARY" | tk="BIT" | tk="BLOCK" | tk="BROWSE" | tk="BUFFERS" | tk="BY" | tk="BYTE" | tk="BYTES" | tk="CACHE" | tk="CALL" | tk="CASCADE" | tk="CASE" | tk="CAST" | tk="CHANGE" | tk="CHANGES" | tk="CHAR" | tk="CHARACTER" | tk="CHECKPOINT" | tk="CLOSE" | tk="COLLATE" | tk="COLUMN" | tk="COLUMNS" | tk="COMMENT" | tk="COMMIT" | tk="CONCURRENTLY" | tk="CONFLICT" | tk="CONSTRAINTS" | tk="CONVERT" | tk="COSTS" | tk="CS" | tk="CYCLE" | tk="DATA" | tk="DATABASE" | tk="DDL" | tk="DECLARE" | tk="DEFAULT" | tk="DEFERRABLE" | tk="DELAYED" | tk="DELETE" | tk="DESC" | tk="DESCRIBE" | tk="DISABLE" | tk="DISCONNECT" | tk="DIV" | tk="DML" | tk="DO" | tk="DOMAIN" | tk="DROP" | tk="DUMP" | tk="DUPLICATE" | tk="ELEMENTS" | tk="EMIT" | tk="ENABLE" | tk="END" | tk="ESCAPE" | tk="EXCLUDE" | tk="EXEC" | tk="EXECUTE" | tk="EXPLAIN" | tk="EXPLICIT" | tk="EXTENDED" | tk="EXTRACT" | tk="FALSE" | tk="FILTER" | tk="FIRST" | tk="FLUSH" | tk="FN" | tk="FOLLOWING" | tk="FORMAT" | tk="FULLTEXT" | tk="FUNCTION" | tk="GRANT" | tk="GUARD" | tk="HASH" | tk="HISTORY" | tk="HOPPING" | tk="INCLUDE" | tk="INCREMENT" | tk="INDEX" | tk="INSERT" | tk="INTERLEAVE" | tk="INTERPRET" | tk="INVALIDATE" | tk="ISNULL" | tk="JSON" | tk="KEEP" | tk="KEY" | tk="KEYS" | tk="LAST" | tk="LEADING" | tk="LINK" | tk="LOCAL" | tk="LOCKED" | tk="LOG" | tk="LOOP" | tk="MATCH" | tk="MATCHED" | tk="MATERIALIZED" | tk="MAXVALUE" | tk="MEMBER" | tk="MERGE" | tk="MINVALUE" | tk="MODIFY" | tk="MOVEMENT" | tk="NEXT" | tk="NO" | tk="NOCACHE" | tk="NOKEEP" | tk="NOLOCK" | tk="NOMAXVALUE" | tk="NOMINVALUE" | tk="NOORDER" | tk="NOTHING" | tk="NOTNULL" | tk="NOVALIDATE" | tk="NOWAIT" | tk="NULLS" | tk="OF" | tk="OFF" | tk="OPEN" | tk="OVER" | tk="OVERLAPS" | tk="PARALLEL" | tk="PARENT" | tk="PARTITION" | tk="PATH" | tk="PERCENT" | tk="PLACING" | tk="PRECEDING" | tk="PRECISION" | tk="PRIMARY" | tk="PRIOR" | tk="PURGE" | tk="QUERY" | tk="QUICK" | tk="QUIESCE" | tk="RANGE" | tk="RAW" | tk="READ" | tk="RECYCLEBIN" | tk="REFERENCES" | tk="REFRESH" | tk="REGISTER" | tk="REMOTE" | tk="RENAME" | tk="REPEATABLE" | tk="REPLACE" | tk="RESET" | tk="RESTART" | tk="RESTRICT" | tk="RESTRICTED" | tk="RESUMABLE" | tk="RESUME" | tk="RETURN" | tk="RLIKE" | tk="ROLLBACK" | tk="ROOT" | tk="ROW" | tk="ROWS" | tk="RR" | tk="RS" | tk="SAVEPOINT" | tk="SCHEMA" | tk="SEED" | tk="SEPARATOR" | tk="SEQUENCE" | tk="SESSION" | tk="SETS" | tk="SHOW" | tk="SHUTDOWN" | tk="SIBLINGS" | tk="SIGNED" | tk="SIMILAR" | tk="SIZE" | tk="SKIP" | tk="STORED" | tk="STRING" | tk="SUSPEND" | tk="SWITCH" | tk="SYNONYM" | tk="SYSTEM" | tk="TABLE" | tk="TABLESPACE" | tk="TEMP" | tk="TEMPORARY" | tk="THEN" | tk="TIMEOUT" | tk="TIMESTAMPTZ" | tk="TO" | tk="TRIGGER" | tk="TRUE" | tk="TRUNCATE" | tk="TUMBLING" | tk="TYPE" | tk="UNLOGGED" | tk="UNQIESCE" | tk="UNSIGNED" | tk="UPDATE" | tk="UPSERT" | tk="UR" | tk="USER" | tk="VALIDATE" | tk="VERBOSE" | tk="VIEW" | tk="WAIT" | tk="WITHIN" | tk="WITHOUT" | tk="WORK" | tk="XML" | tk="XMLAGG" | tk="XMLDATA" | tk="XMLSCHEMA" | tk="XMLTEXT" | tk="XSINIL" | tk="YAML" | tk="YES" | tk="ZONE" ) + | tk="ACTION" | tk="ACTIVE" | tk="ADD" | tk="ADVANCE" | tk="ADVISE" | tk="AGAINST" | tk="ALGORITHM" | tk="ALTER" | tk="ANALYZE" | tk="APPLY" | tk="ARCHIVE" | tk="ARRAY" | tk="ASC" | tk="AT" | tk="AUTHORIZATION" | tk="AUTO" | tk="BEGIN" | tk="BERNOULLI" | tk="BINARY" | tk="BIT" | tk="BLOCK" | tk="BROWSE" | tk="BUFFERS" | tk="BY" | tk="BYTE" | tk="BYTES" | tk="CACHE" | tk="CALL" | tk="CASCADE" | tk="CASE" | tk="CAST" | tk="CHANGE" | tk="CHANGES" | tk="CHAR" | tk="CHARACTER" | tk="CHECKPOINT" | tk="CLOSE" | tk="COLLATE" | tk="COLUMN" | tk="COLUMNS" | tk="COMMENT" | tk="COMMIT" | tk="CONCURRENTLY" | tk="CONFLICT" | tk="CONSTRAINTS" | tk="CONVERT" | tk="COSTS" | tk="CS" | tk="CYCLE" | tk="DATA" | tk="DATABASE" | tk="DDL" | tk="DECLARE" | tk="DEFAULT" | tk="DEFERRABLE" | tk="DELAYED" | tk="DELETE" | tk="DESC" | tk="DESCRIBE" | tk="DISABLE" | tk="DISCONNECT" | tk="DIV" | tk="DML" | tk="DO" | tk="DOMAIN" | tk="DROP" | tk="DUMP" | tk="DUPLICATE" | tk="ELEMENTS" | tk="EMIT" | tk="ENABLE" | tk="END" | tk="ESCAPE" | tk="EXCLUDE" | tk="EXEC" | tk="EXECUTE" | tk="EXPLAIN" | tk="EXPLICIT" | tk="EXTENDED" | tk="EXTRACT" | tk="FALSE" | tk="FILTER" | tk="FIRST" | tk="FLUSH" | tk="FN" | tk="FOLLOWING" | tk="FORMAT" | tk="FULLTEXT" | tk="FUNCTION" | tk="GRANT" | tk="GUARD" | tk="HASH" | tk="HISTORY" | tk="HOPPING" | tk="INCLUDE" | tk="INCREMENT" | tk="INDEX" | tk="INSERT" | tk="INTERLEAVE" | tk="INTERPRET" | tk="INVALIDATE" | tk="ISNULL" | tk="JSON" | tk="KEEP" | tk="KEY" | tk="KEYS" | tk="LAST" | tk="LEADING" | tk="LINK" | tk="LOCAL" | tk="LOCK" | tk="LOCKED" | tk="LOG" | tk="LOOP" | tk="MATCH" | tk="MATCHED" | tk="MATERIALIZED" | tk="MAXVALUE" | tk="MEMBER" | tk="MERGE" | tk="MINVALUE" | tk="MODE" | tk="MODIFY" | tk="MOVEMENT" | tk="NEXT" | tk="NO" | tk="NOCACHE" | tk="NOKEEP" | tk="NOLOCK" | tk="NOMAXVALUE" | tk="NOMINVALUE" | tk="NOORDER" | tk="NOTHING" | tk="NOTNULL" | tk="NOVALIDATE" | tk="NOWAIT" | tk="NULLS" | tk="OF" | tk="OFF" | tk="OPEN" | tk="OVER" | tk="OVERLAPS" | tk="PARALLEL" | tk="PARENT" | tk="PARTITION" | tk="PATH" | tk="PERCENT" | tk="PLACING" | tk="PRECEDING" | tk="PRECISION" | tk="PRIMARY" | tk="PRIOR" | tk="PURGE" | tk="QUERY" | tk="QUICK" | tk="QUIESCE" | tk="RANGE" | tk="RAW" | tk="READ" | tk="RECYCLEBIN" | tk="REFERENCES" | tk="REFRESH" | tk="REGISTER" | tk="REMOTE" | tk="RENAME" | tk="REPEATABLE" | tk="REPLACE" | tk="RESET" | tk="RESTART" | tk="RESTRICT" | tk="RESTRICTED" | tk="RESUMABLE" | tk="RESUME" | tk="RETURN" | tk="RLIKE" | tk="ROLLBACK" | tk="ROOT" | tk="ROW" | tk="ROWS" | tk="RR" | tk="RS" | tk="SAVEPOINT" | tk="SCHEMA" | tk="SEED" | tk="SEPARATOR" | tk="SEQUENCE" | tk="SESSION" | tk="SETS" | tk="SHARE" | tk="SHOW" | tk="SHUTDOWN" | tk="SIBLINGS" | tk="SIGNED" | tk="SIMILAR" | tk="SIZE" | tk="SKIP" | tk="STORED" | tk="STRING" | tk="SUSPEND" | tk="SWITCH" | tk="SYNONYM" | tk="SYSTEM" | tk="TABLE" | tk="TABLESPACE" | tk="TEMP" | tk="TEMPORARY" | tk="THEN" | tk="TIMEOUT" | tk="TIMESTAMPTZ" | tk="TO" | tk="TRIGGER" | tk="TRUE" | tk="TRUNCATE" | tk="TUMBLING" | tk="TYPE" | tk="UNLOGGED" | tk="UNQIESCE" | tk="UNSIGNED" | tk="UPDATE" | tk="UPSERT" | tk="UR" | tk="USER" | tk="VALIDATE" | tk="VERBOSE" | tk="VIEW" | tk="WAIT" | tk="WITHIN" | tk="WITHOUT" | tk="WORK" | tk="XML" | tk="XMLAGG" | tk="XMLDATA" | tk="XMLSCHEMA" | tk="XMLTEXT" | tk="XSINIL" | tk="YAML" | tk="YES" | tk="ZONE" ) { return tk.image; } } @@ -2268,13 +2269,16 @@ PlainSelect PlainSelect() #PlainSelect: [ LOOKAHEAD(, { limit==null }) limit = LimitWithOffset() { plainSelect.setLimit(limit); } ] [ LOOKAHEAD() fetch = Fetch() { plainSelect.setFetch(fetch); } ] [ LOOKAHEAD( ) withIsolation = WithIsolation() { plainSelect.setIsolation(withIsolation); } ] - [ LOOKAHEAD(2) { plainSelect.setForUpdate(true); } + [ LOOKAHEAD(2) ( + { plainSelect.setForUpdate(true); } | { plainSelect.setForShare(true); } | + ( { plainSelect.setForNoKeyUpdate(true); }) | + ( { plainSelect.setForKeyShare(true); }) + ) [ LOOKAHEAD(2) updateTable = Table() { plainSelect.setForUpdateTable(updateTable); } ] [ LOOKAHEAD() wait = Wait() { plainSelect.setWait(wait); } ] [ LOOKAHEAD(2) ( { plainSelect.setNoWait(true); } | { plainSelect.setSkipLocked(true); }) ] ] - [ LOOKAHEAD() optimize = OptimizeFor() { plainSelect.setOptimizeFor(optimize); } ] { plainSelect.setSelectItems(selectItems); diff --git a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java index 5fb760b93..0976a8cbb 100644 --- a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java @@ -4804,6 +4804,14 @@ public void testCurrentIssue940() throws JSQLParserException { "SELECT date(current) AS test_date FROM systables WHERE tabid = 1"); } + @Test + public void testIssue1878() throws JSQLParserException { + assertSqlCanBeParsedAndDeparsed("SELECT * FROM MY_TABLE1 FOR SHARE"); + // PostgreSQL ONLY + assertSqlCanBeParsedAndDeparsed("SELECT * FROM MY_TABLE1 FOR NO KEY UPDATE"); + assertSqlCanBeParsedAndDeparsed("SELECT * FROM MY_TABLE1 FOR KEY SHARE"); + } + @Test public void testKeyWordView() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed( diff --git a/src/test/java/net/sf/jsqlparser/util/validation/validator/SelectValidatorTest.java b/src/test/java/net/sf/jsqlparser/util/validation/validator/SelectValidatorTest.java index a22b34156..7b9f2902e 100644 --- a/src/test/java/net/sf/jsqlparser/util/validation/validator/SelectValidatorTest.java +++ b/src/test/java/net/sf/jsqlparser/util/validation/validator/SelectValidatorTest.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.util.validation.validator; import java.util.Arrays; + import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.feature.Feature; import net.sf.jsqlparser.util.validation.ValidationTestAsserts; @@ -68,6 +69,25 @@ public void testValidationForUpdateWaitWithTimeout() throws JSQLParserException validateNoErrors(sql, 1, DatabaseType.ORACLE, DatabaseType.MARIADB); } + @Test + public void testValidationForShare() throws JSQLParserException { + String sql = "SELECT * FROM mytable FOR SHARE"; + validateNoErrors(sql, 1, DatabaseType.MYSQL, DatabaseType.POSTGRESQL); + } + + @Test + public void testValidationForPostgresShare() throws JSQLParserException { + String sql = "SELECT * FROM mytable FOR KEY SHARE"; + validateNoErrors(sql, 1, DatabaseType.POSTGRESQL); + + String sql2 = "SELECT * FROM mytable FOR NO KEY UPDATE"; + validateNoErrors(sql2, 1, DatabaseType.POSTGRESQL); + + // Not familiar with oracle, please modify if supported. + validateNotSupported(sql2, 1, 1, DatabaseType.ORACLE, + Feature.selectForNoKeyUpdate); + } + @Test public void testValidationForUpdateNoWait() throws JSQLParserException { String sql = "SELECT * FROM mytable FOR UPDATE NOWAIT"; @@ -83,7 +103,8 @@ public void testValidationJoinOuterSimple() throws JSQLParserException { @Test public void testValidationJoin() throws JSQLParserException { - for (String sql : Arrays.asList("SELECT t1.col, t2.col, t1.id FROM tab1 t1, tab2 t2 WHERE t1.id = t2.id", + for (String sql : Arrays.asList( + "SELECT t1.col, t2.col, t1.id FROM tab1 t1, tab2 t2 WHERE t1.id = t2.id", "SELECT t1.col, t2.col, t1.id FROM tab1 t1 JOIN tab2 t2 ON t1.id = t2.id", "SELECT t1.col, t2.col, t1.id FROM tab1 t1 INNER JOIN tab2 t2 ON t1.id = t2.id")) { validateNoErrors(sql, 1, DatabaseType.DATABASES); @@ -92,7 +113,8 @@ public void testValidationJoin() throws JSQLParserException { @Test public void testOracleHierarchicalQuery() throws JSQLParserException { - String sql = "SELECT last_name, employee_id, manager_id, LEVEL FROM employees START WITH employee_id = 100 CONNECT BY PRIOR employee_id = manager_id ORDER SIBLINGS BY last_name"; + String sql = + "SELECT last_name, employee_id, manager_id, LEVEL FROM employees START WITH employee_id = 100 CONNECT BY PRIOR employee_id = manager_id ORDER SIBLINGS BY last_name"; validateNoErrors(sql, 1, DatabaseType.ORACLE); } @@ -127,7 +149,8 @@ public void testValidationWith() throws JSQLParserException { @Test public void testValidationWithRecursive() throws JSQLParserException { - String statement = "WITH RECURSIVE t (n) AS ((SELECT 1) UNION ALL (SELECT n + 1 FROM t WHERE n < 100)) SELECT sum(n) FROM t"; + String statement = + "WITH RECURSIVE t (n) AS ((SELECT 1) UNION ALL (SELECT n + 1 FROM t WHERE n < 100)) SELECT sum(n) FROM t"; validateNoErrors(statement, 1, DatabaseType.H2, DatabaseType.MARIADB, DatabaseType.MYSQL, DatabaseType.SQLSERVER, DatabaseType.POSTGRESQL); validateNotSupported(statement, 1, 1, DatabaseType.ORACLE, Feature.withItemRecursive); @@ -135,7 +158,8 @@ public void testValidationWithRecursive() throws JSQLParserException { @Test public void testSelectMulipleExpressionList() { - String sql = "SELECT * FROM mytable WHERE (SSN, SSM) IN (('11111111111111', '22222222222222'))"; + String sql = + "SELECT * FROM mytable WHERE (SSN, SSM) IN (('11111111111111', '22222222222222'))"; validateNoErrors(sql, 1, DatabaseType.DATABASES); } @@ -148,7 +172,8 @@ public void testValidatePivotWithAlias() throws JSQLParserException { @Test public void testValidatePivotXml() throws JSQLParserException { - validateNoErrors("SELECT * FROM mytable PIVOT XML (count(a) FOR b IN ('val1'))", 1, DatabaseType.SQLSERVER); + validateNoErrors("SELECT * FROM mytable PIVOT XML (count(a) FOR b IN ('val1'))", 1, + DatabaseType.SQLSERVER); } @Test @@ -160,14 +185,17 @@ public void testValidateUnPivot() throws JSQLParserException { @Test public void testValidateSubJoin() throws JSQLParserException { - validateNoErrors("SELECT * FROM ((tabc c INNER JOIN tabn n ON n.ref = c.id) INNER JOIN taba a ON a.REF = c.id)", + validateNoErrors( + "SELECT * FROM ((tabc c INNER JOIN tabn n ON n.ref = c.id) INNER JOIN taba a ON a.REF = c.id)", 1, DatabaseType.SQLSERVER); } @Test public void testValidateTableFunction() { - for (String sql : Arrays.asList("SELECT f2 FROM SOME_FUNCTION()", "SELECT f2 FROM SOME_FUNCTION(1, 'val')")) { - validateNoErrors(sql, 1, DatabaseType.POSTGRESQL, DatabaseType.H2, DatabaseType.SQLSERVER); + for (String sql : Arrays.asList("SELECT f2 FROM SOME_FUNCTION()", + "SELECT f2 FROM SOME_FUNCTION(1, 'val')")) { + validateNoErrors(sql, 1, DatabaseType.POSTGRESQL, DatabaseType.H2, + DatabaseType.SQLSERVER); } } @@ -182,11 +210,11 @@ public void testValidateLateral() throws JSQLParserException { public void testValidateIssue1502() throws JSQLParserException { validateNoErrors( "select b.id, name ,(select name from Blog where name = 'sadf') as name2 " - + ", category, owner, b.update_time " - + "from Blog as b " - + "left join Content " - + "ON b.id = Content.blog_id " - + "where name = 'sadf' order by Content.title desc", + + ", category, owner, b.update_time " + + "from Blog as b " + + "left join Content " + + "ON b.id = Content.blog_id " + + "where name = 'sadf' order by Content.title desc", 1, DatabaseType.POSTGRESQL); - } + } } From 92597dcf61b643708974b0b69cb7aadfc766f135 Mon Sep 17 00:00:00 2001 From: jxnu-liguobin Date: Sat, 16 Dec 2023 18:39:12 +0800 Subject: [PATCH 2/5] optimize use way --- .../jsqlparser/statement/select/ForMode.java | 34 +++++++++++ .../statement/select/PlainSelect.java | 60 ++++--------------- .../util/deparser/SelectDeParser.java | 19 +----- .../validation/validator/SelectValidator.java | 14 +++-- .../net/sf/jsqlparser/parser/JSqlParserCC.jjt | 13 ++-- .../statement/select/SelectTest.java | 20 ++++++- .../validator/SelectValidatorTest.java | 1 - 7 files changed, 79 insertions(+), 82 deletions(-) create mode 100644 src/main/java/net/sf/jsqlparser/statement/select/ForMode.java diff --git a/src/main/java/net/sf/jsqlparser/statement/select/ForMode.java b/src/main/java/net/sf/jsqlparser/statement/select/ForMode.java new file mode 100644 index 000000000..a58233ed1 --- /dev/null +++ b/src/main/java/net/sf/jsqlparser/statement/select/ForMode.java @@ -0,0 +1,34 @@ +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2023 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.statement.select; + +/** + * @author jxnu-liguobin + */ +public enum ForMode { + + UPDATE("UPDATE"), + + SHARE("SHARE"), + + NO_KEY_UPDATE("NO KEY UPDATE"), + + KEY_SHARE("KEY SHARE"); + + private final String value; + + public String getValue() { + return value; + } + + ForMode(String s) { + this.value = s; + } +} diff --git a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java index 067175dd0..ee59b7894 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java @@ -45,10 +45,7 @@ public class PlainSelect extends Select { private Top top; private OracleHierarchicalExpression oracleHierarchical = null; private OracleHint oracleHint = null; - private boolean forUpdate = false; - private boolean forShare = false; - private boolean forNoKeyUpdate = false; - private boolean forKeyShare = false; + private ForMode forMode = null; private Table forUpdateTable = null; private boolean skipLocked; private Wait wait; @@ -314,12 +311,12 @@ public void setOracleHierarchical(OracleHierarchicalExpression oracleHierarchica this.oracleHierarchical = oracleHierarchical; } - public boolean isForUpdate() { - return forUpdate; + public ForMode getForMode() { + return forMode; } - public void setForUpdate(boolean forUpdate) { - this.forUpdate = forUpdate; + public void setForMode(ForMode forMode) { + this.forMode = forMode; } public Table getForUpdateTable() { @@ -488,22 +485,9 @@ public StringBuilder appendSelectBodyTo(StringBuilder builder) { if (emitChanges) { builder.append(" EMIT CHANGES"); } - if (isForUpdate() || isForShare() || isForKeyShare() || isForNoKeyUpdate()) { + if (getForMode() != null) { builder.append(" FOR "); - String type = null; - if (isForUpdate()) { - type = "UPDATE"; - } - if (isForShare()) { - type = "SHARE"; - } - if (isForKeyShare()) { - type = "KEY SHARE"; - } - if (isForNoKeyUpdate()) { - type = "NO KEY UPDATE"; - } - builder.append(type); + builder.append(getForMode().getValue()); if (forUpdateTable != null) { builder.append(" OF ").append(forUpdateTable); @@ -636,12 +620,12 @@ public PlainSelect withOracleSiblings(boolean oracleSiblings) { return this; } - public PlainSelect withForUpdate(boolean forUpdate) { - this.setForUpdate(forUpdate); + public PlainSelect withForMode(ForMode forUpdate) { + this.setForMode(forUpdate); return this; } - public PlainSelect withForUpdateTable(Table forUpdateTable) { + public PlainSelect withForModeTable(Table forUpdateTable) { this.setForUpdateTable(forUpdateTable); return this; } @@ -701,30 +685,6 @@ public PlainSelect addJoins(Collection joins) { return this.withJoins(collection); } - public boolean isForShare() { - return forShare; - } - - public void setForShare(boolean forShare) { - this.forShare = forShare; - } - - public boolean isForNoKeyUpdate() { - return forNoKeyUpdate; - } - - public void setForNoKeyUpdate(boolean forNoKeyUpdate) { - this.forNoKeyUpdate = forNoKeyUpdate; - } - - public boolean isForKeyShare() { - return forKeyShare; - } - - public void setForKeyShare(boolean forKeyShare) { - this.forKeyShare = forKeyShare; - } - public E getFromItem(Class type) { return type.cast(getFromItem()); } diff --git a/src/main/java/net/sf/jsqlparser/util/deparser/SelectDeParser.java b/src/main/java/net/sf/jsqlparser/util/deparser/SelectDeParser.java index ee591351e..a6b718baf 100644 --- a/src/main/java/net/sf/jsqlparser/util/deparser/SelectDeParser.java +++ b/src/main/java/net/sf/jsqlparser/util/deparser/SelectDeParser.java @@ -268,24 +268,9 @@ public void visit(PlainSelect plainSelect) { buffer.append(plainSelect.getWindowDefinitions().stream() .map(WindowDefinition::toString).collect(joining(", "))); } - if (plainSelect.isForUpdate() || plainSelect.isForShare() || plainSelect.isForNoKeyUpdate() - || plainSelect.isForKeyShare()) { + if (plainSelect.getForMode() != null) { buffer.append(" FOR "); - - String type = null; - if (plainSelect.isForUpdate()) { - type = "UPDATE"; - } - if (plainSelect.isForShare()) { - type = "SHARE"; - } - if (plainSelect.isForKeyShare()) { - type = "KEY SHARE"; - } - if (plainSelect.isForNoKeyUpdate()) { - type = "NO KEY UPDATE"; - } - buffer.append(type); + buffer.append(plainSelect.getForMode().getValue()); if (plainSelect.getForUpdateTable() != null) { buffer.append(" OF ").append(plainSelect.getForUpdateTable()); diff --git a/src/main/java/net/sf/jsqlparser/util/validation/validator/SelectValidator.java b/src/main/java/net/sf/jsqlparser/util/validation/validator/SelectValidator.java index 4ca4275c6..97fcd08a3 100644 --- a/src/main/java/net/sf/jsqlparser/util/validation/validator/SelectValidator.java +++ b/src/main/java/net/sf/jsqlparser/util/validation/validator/SelectValidator.java @@ -10,7 +10,6 @@ package net.sf.jsqlparser.util.validation.validator; import java.util.List; - import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.MySQLIndexHint; import net.sf.jsqlparser.expression.SQLServerHints; @@ -18,6 +17,7 @@ import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.ExceptOp; import net.sf.jsqlparser.statement.select.Fetch; +import net.sf.jsqlparser.statement.select.ForMode; import net.sf.jsqlparser.statement.select.FromItemVisitor; import net.sf.jsqlparser.statement.select.IntersectOp; import net.sf.jsqlparser.statement.select.Join; @@ -86,12 +86,14 @@ public void visit(PlainSelect plainSelect) { isNotEmpty(plainSelect.getOrderByElements()) && plainSelect.isOracleSiblings(), Feature.oracleOrderBySiblings); - if (plainSelect.isForUpdate() || plainSelect.isForKeyShare() - || plainSelect.isForNoKeyUpdate() || plainSelect.isForShare()) { + if (plainSelect.getForMode() != null) { validateFeature(c, Feature.selectForUpdate); - validateFeature(c, plainSelect.isForKeyShare(), Feature.selectForKeyShare); - validateFeature(c, plainSelect.isForNoKeyUpdate(), Feature.selectForNoKeyUpdate); - validateFeature(c, plainSelect.isForShare(), Feature.selectForShare); + validateFeature(c, plainSelect.getForMode() == ForMode.KEY_SHARE, + Feature.selectForKeyShare); + validateFeature(c, plainSelect.getForMode() == ForMode.NO_KEY_UPDATE, + Feature.selectForNoKeyUpdate); + validateFeature(c, plainSelect.getForMode() == ForMode.SHARE, + Feature.selectForShare); validateOptionalFeature(c, plainSelect.getForUpdateTable(), Feature.selectForUpdateOfTable); diff --git a/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt b/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt index f84598902..ad394b56b 100644 --- a/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt +++ b/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt @@ -2269,11 +2269,14 @@ PlainSelect PlainSelect() #PlainSelect: [ LOOKAHEAD(, { limit==null }) limit = LimitWithOffset() { plainSelect.setLimit(limit); } ] [ LOOKAHEAD() fetch = Fetch() { plainSelect.setFetch(fetch); } ] [ LOOKAHEAD( ) withIsolation = WithIsolation() { plainSelect.setIsolation(withIsolation); } ] - [ LOOKAHEAD(2) ( - { plainSelect.setForUpdate(true); } | { plainSelect.setForShare(true); } | - ( { plainSelect.setForNoKeyUpdate(true); }) | - ( { plainSelect.setForKeyShare(true); }) - ) + [ LOOKAHEAD(2) + + ( + { plainSelect.setForMode(ForMode.UPDATE); } + | { plainSelect.setForMode(ForMode.SHARE); } + | ( { plainSelect.setForMode(ForMode.NO_KEY_UPDATE); }) + | ( { plainSelect.setForMode(ForMode.KEY_SHARE); }) + ) [ LOOKAHEAD(2) updateTable = Table() { plainSelect.setForUpdateTable(updateTable); } ] [ LOOKAHEAD() wait = Wait() { plainSelect.setWait(wait); } ] [ LOOKAHEAD(2) ( { plainSelect.setNoWait(true); } diff --git a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java index 0976a8cbb..440025897 100644 --- a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java @@ -22,6 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -4812,6 +4813,19 @@ public void testIssue1878() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT * FROM MY_TABLE1 FOR KEY SHARE"); } + @Test + public void testIssue1878ViaJava() throws JSQLParserException { + String expectedSQLStr = "SELECT * FROM MY_TABLE1 FOR SHARE"; + + // Step 1: generate the Java Object Hierarchy for + Table table = new Table().withName("MY_TABLE1"); + + PlainSelect select = new PlainSelect().addSelectItem(new AllColumns()) + .withFromItem(table).withForMode(ForMode.KEY_SHARE).withForMode(ForMode.SHARE); + + Assertions.assertEquals(expectedSQLStr, select.toString()); + } + @Test public void testKeyWordView() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed( @@ -5572,7 +5586,7 @@ public void testSelectStatementWithForUpdateAndSkipLockedTokens() throws JSQLPar Select select = (Select) CCJSqlParserUtil.parse(sql); PlainSelect plainSelect = (PlainSelect) select; - assertTrue(plainSelect.isForUpdate()); + assertSame(plainSelect.getForMode(), ForMode.UPDATE); assertTrue(plainSelect.isSkipLocked()); } @@ -5584,7 +5598,7 @@ public void testSelectStatementWithForUpdateButWithoutSkipLockedTokens() Select select = (Select) CCJSqlParserUtil.parse(sql); PlainSelect plainSelect = (PlainSelect) select; - assertTrue(plainSelect.isForUpdate()); + assertSame(plainSelect.getForMode(), ForMode.UPDATE); assertFalse(plainSelect.isSkipLocked()); } @@ -5596,7 +5610,7 @@ public void testSelectStatementWithoutForUpdateAndSkipLockedTokens() Select select = (Select) CCJSqlParserUtil.parse(sql); PlainSelect plainSelect = (PlainSelect) select; - assertFalse(plainSelect.isForUpdate()); + assertNotNull(plainSelect.getForMode()); assertFalse(plainSelect.isSkipLocked()); } diff --git a/src/test/java/net/sf/jsqlparser/util/validation/validator/SelectValidatorTest.java b/src/test/java/net/sf/jsqlparser/util/validation/validator/SelectValidatorTest.java index 7b9f2902e..52b7a5396 100644 --- a/src/test/java/net/sf/jsqlparser/util/validation/validator/SelectValidatorTest.java +++ b/src/test/java/net/sf/jsqlparser/util/validation/validator/SelectValidatorTest.java @@ -10,7 +10,6 @@ package net.sf.jsqlparser.util.validation.validator; import java.util.Arrays; - import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.feature.Feature; import net.sf.jsqlparser.util.validation.ValidationTestAsserts; From 665629894c53ed598a21a1257ee8065dcb414270 Mon Sep 17 00:00:00 2001 From: jxnu-liguobin Date: Sat, 16 Dec 2023 18:42:14 +0800 Subject: [PATCH 3/5] optimize use way --- .../java/net/sf/jsqlparser/statement/select/PlainSelect.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java index ee59b7894..1543dc414 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java @@ -625,7 +625,7 @@ public PlainSelect withForMode(ForMode forUpdate) { return this; } - public PlainSelect withForModeTable(Table forUpdateTable) { + public PlainSelect withForUpdateTable(Table forUpdateTable) { this.setForUpdateTable(forUpdateTable); return this; } From 512825812a9c6481cacd3acee1f48879df533bca Mon Sep 17 00:00:00 2001 From: jxnu-liguobin Date: Sat, 16 Dec 2023 18:44:16 +0800 Subject: [PATCH 4/5] fix test --- .../java/net/sf/jsqlparser/statement/select/SelectTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java index 440025897..59f6022b8 100644 --- a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java @@ -5610,7 +5610,7 @@ public void testSelectStatementWithoutForUpdateAndSkipLockedTokens() Select select = (Select) CCJSqlParserUtil.parse(sql); PlainSelect plainSelect = (PlainSelect) select; - assertNotNull(plainSelect.getForMode()); + assertNull(plainSelect.getForMode()); assertFalse(plainSelect.isSkipLocked()); } From e51ec2a6d9fb7cf35642f72ecda5a716439bb2c0 Mon Sep 17 00:00:00 2001 From: jxnu-liguobin Date: Sat, 16 Dec 2023 18:47:56 +0800 Subject: [PATCH 5/5] fix param name --- .../java/net/sf/jsqlparser/statement/select/PlainSelect.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java index 1543dc414..72a4e530c 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java @@ -620,8 +620,8 @@ public PlainSelect withOracleSiblings(boolean oracleSiblings) { return this; } - public PlainSelect withForMode(ForMode forUpdate) { - this.setForMode(forUpdate); + public PlainSelect withForMode(ForMode forMode) { + this.setForMode(forMode); return this; }