|
| 1 | +/*- |
| 2 | + * #%L |
| 3 | + * JSQLParser library |
| 4 | + * %% |
| 5 | + * Copyright (C) 2004 - 2026 JSQLParser |
| 6 | + * %% |
| 7 | + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 |
| 8 | + * #L% |
| 9 | + */ |
| 10 | +package net.sf.jsqlparser.statement.create; |
| 11 | + |
| 12 | +import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; |
| 13 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 14 | +import static org.junit.jupiter.api.Assertions.assertFalse; |
| 15 | +import static org.junit.jupiter.api.Assertions.assertInstanceOf; |
| 16 | +import static org.junit.jupiter.api.Assertions.assertNull; |
| 17 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 18 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 19 | + |
| 20 | +import java.util.ArrayList; |
| 21 | +import java.util.List; |
| 22 | +import net.sf.jsqlparser.JSQLParserException; |
| 23 | +import net.sf.jsqlparser.expression.CastExpression; |
| 24 | +import net.sf.jsqlparser.expression.Expression; |
| 25 | +import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; |
| 26 | +import net.sf.jsqlparser.expression.ExtractExpression; |
| 27 | +import net.sf.jsqlparser.expression.Function; |
| 28 | +import net.sf.jsqlparser.expression.LongValue; |
| 29 | +import net.sf.jsqlparser.parser.AbstractJSqlParser.Dialect; |
| 30 | +import net.sf.jsqlparser.parser.CCJSqlParserUtil; |
| 31 | +import net.sf.jsqlparser.parser.feature.Feature; |
| 32 | +import net.sf.jsqlparser.parser.feature.FeatureConfiguration; |
| 33 | +import net.sf.jsqlparser.schema.Column; |
| 34 | +import net.sf.jsqlparser.schema.Sequence; |
| 35 | +import net.sf.jsqlparser.statement.Statement; |
| 36 | +import net.sf.jsqlparser.statement.StatementVisitorAdapter; |
| 37 | +import net.sf.jsqlparser.statement.alter.Alter; |
| 38 | +import net.sf.jsqlparser.statement.alter.AlterExpressionPartition; |
| 39 | +import net.sf.jsqlparser.statement.create.index.CreateIndex; |
| 40 | +import net.sf.jsqlparser.statement.create.table.CreateTable; |
| 41 | +import net.sf.jsqlparser.statement.create.table.IdentityDefinition; |
| 42 | +import net.sf.jsqlparser.statement.create.table.KeyElement; |
| 43 | +import net.sf.jsqlparser.statement.create.table.PartitionBound; |
| 44 | +import net.sf.jsqlparser.statement.select.SelectVisitorAdapter; |
| 45 | +import net.sf.jsqlparser.util.TablesNamesFinder; |
| 46 | +import net.sf.jsqlparser.util.deparser.ExpressionDeParser; |
| 47 | +import net.sf.jsqlparser.util.deparser.SelectDeParser; |
| 48 | +import net.sf.jsqlparser.util.deparser.StatementDeParser; |
| 49 | +import net.sf.jsqlparser.util.validation.Validation; |
| 50 | +import net.sf.jsqlparser.util.validation.feature.FeaturesAllowed; |
| 51 | +import org.junit.jupiter.api.Test; |
| 52 | +import org.junit.jupiter.params.ParameterizedTest; |
| 53 | +import org.junit.jupiter.params.provider.ValueSource; |
| 54 | + |
| 55 | +/** PostgreSQL DDL options verified against PostgreSQL 18.6. */ |
| 56 | +class PostgreSqlDdlKeyOptionsTest { |
| 57 | + @Test |
| 58 | + void keepsSpecialIndexKeyExpressionsAndAttributes() throws JSQLParserException { |
| 59 | + CreateIndex index = (CreateIndex) checked("CREATE INDEX ix ON t " |
| 60 | + + "(CAST(n AS bigint) int8_ops DESC NULLS LAST, EXTRACT(YEAR FROM d), lower(label))"); |
| 61 | + List<KeyElement> keys = index.getIndex().getColumns(); |
| 62 | + assertEquals(3, keys.size()); |
| 63 | + CastExpression cast = assertInstanceOf(CastExpression.class, keys.get(0).getExpression()); |
| 64 | + assertEquals("n", assertInstanceOf(Column.class, cast.getLeftExpression()).getColumnName()); |
| 65 | + assertEquals("bigint", cast.getColDataType().getDataType()); |
| 66 | + assertEquals("int8_ops", keys.get(0).getOperatorClass()); |
| 67 | + assertEquals(KeyElement.SortOrder.DESC, keys.get(0).getSortOrder()); |
| 68 | + assertEquals(KeyElement.NullOrdering.LAST, keys.get(0).getNullOrdering()); |
| 69 | + ExtractExpression extract = |
| 70 | + assertInstanceOf(ExtractExpression.class, keys.get(1).getExpression()); |
| 71 | + assertEquals("YEAR", extract.getName()); |
| 72 | + assertEquals("d", assertInstanceOf(Column.class, extract.getExpression()).getColumnName()); |
| 73 | + assertInstanceOf(Function.class, keys.get(2).getExpression()); |
| 74 | + keys.forEach(key -> assertFalse(key.isExpressionParenthesized())); |
| 75 | + assertEquals(List.of("n", "d", "label"), visitedColumns(index)); |
| 76 | + assertEquals(java.util.Set.of("t"), new TablesNamesFinder<>().getTables(index)); |
| 77 | + roundTrip(index); |
| 78 | + } |
| 79 | + |
| 80 | + @ParameterizedTest |
| 81 | + @ValueSource(strings = {"CAST(n AS bigint)", "EXTRACT(YEAR FROM d)", "lower(label)"}) |
| 82 | + void sharesSpecialFunctionsWithPartitionKeys(String expression) throws JSQLParserException { |
| 83 | + CreateTable table = (CreateTable) checked("CREATE TABLE t (n integer, d date, label text) " |
| 84 | + + "PARTITION BY RANGE (" + expression + ")"); |
| 85 | + Expression key = table.getPartitioning().getExpression(); |
| 86 | + assertEquals(expression, key.toString()); |
| 87 | + Class<? extends Expression> expressionType = expression.startsWith("CAST") |
| 88 | + ? CastExpression.class |
| 89 | + : expression.startsWith("EXTRACT") ? ExtractExpression.class : Function.class; |
| 90 | + assertInstanceOf(expressionType, key); |
| 91 | + roundTrip(table); |
| 92 | + String operatorClass = key instanceof CastExpression ? "int8_ops" |
| 93 | + : key instanceof ExtractExpression ? "numeric_ops" : "text_ops"; |
| 94 | + CreateTable attributed = |
| 95 | + (CreateTable) checked("CREATE TABLE t (n integer, d date, label text) " |
| 96 | + + "PARTITION BY RANGE (" + expression + " " + operatorClass + ")"); |
| 97 | + assertEquals(operatorClass, |
| 98 | + attributed.getPartitioning().getKeyColumns().get(0).getOperatorClass()); |
| 99 | + assertFalse(attributed.getPartitioning().getKeyColumns().get(0) |
| 100 | + .isExpressionParenthesized()); |
| 101 | + roundTrip(attributed); |
| 102 | + } |
| 103 | + |
| 104 | + @Test |
| 105 | + void specialFunctionNamesStillWorkAsIdentifiers() throws JSQLParserException { |
| 106 | + CreateIndex index = |
| 107 | + (CreateIndex) checked("CREATE INDEX ix ON t (extract, \"CAST\", \"EXTRACT\")"); |
| 108 | + assertEquals(List.of("extract", "\"CAST\"", "\"EXTRACT\""), index.getIndex().getColumns() |
| 109 | + .stream().map(KeyElement::getColumnName) |
| 110 | + .collect(java.util.stream.Collectors.toList())); |
| 111 | + index.getIndex().getColumns().forEach(key -> assertNull(key.getExpression())); |
| 112 | + roundTrip(checked("CREATE TABLE t (extract integer) PARTITION BY RANGE (extract)")); |
| 113 | + CreateIndex calls = |
| 114 | + (CreateIndex) checked("CREATE INDEX ix ON t (\"CAST\"(n), \"EXTRACT\"(d))"); |
| 115 | + calls.getIndex().getColumns() |
| 116 | + .forEach(key -> assertInstanceOf(Function.class, key.getExpression())); |
| 117 | + } |
| 118 | + |
| 119 | + @Test |
| 120 | + void expressionVisitorsAndDeparsersReachSpecialKeys() throws JSQLParserException { |
| 121 | + for (String sql : new String[] { |
| 122 | + "CREATE INDEX ix ON t (CAST(n AS bigint), EXTRACT(YEAR FROM d))", |
| 123 | + "CREATE TABLE t (n integer, d date) PARTITION BY RANGE " |
| 124 | + + "(CAST(n AS bigint), EXTRACT(YEAR FROM d))"}) { |
| 125 | + Statement statement = checked(sql); |
| 126 | + assertEquals(List.of("n", "d"), visitedColumns(statement)); |
| 127 | + StringBuilder output = new StringBuilder(); |
| 128 | + ExpressionDeParser expressions = new ExpressionDeParser() { |
| 129 | + @Override |
| 130 | + public <S> StringBuilder visit(Column column, S context) { |
| 131 | + return getBuilder().append("mapped_").append(column.getColumnName()); |
| 132 | + } |
| 133 | + }; |
| 134 | + statement.accept(new StatementDeParser(expressions, new SelectDeParser(), output), |
| 135 | + null); |
| 136 | + assertEquals(sql.replace("CAST(n ", "CAST(mapped_n ") |
| 137 | + .replace("FROM d)", "FROM mapped_d)"), output.toString()); |
| 138 | + roundTrip(parse(output.toString())); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + @ParameterizedTest |
| 143 | + @ValueSource(strings = {"n + 1", "CAST(n AS bigint) + 1", "EXTRACT(YEAR FROM d) + 1"}) |
| 144 | + void arbitraryBareExpressionsStillNeedParentheses(String expression) |
| 145 | + throws JSQLParserException { |
| 146 | + assertThrows(JSQLParserException.class, |
| 147 | + () -> parse("CREATE INDEX ix ON t (" + expression + ")")); |
| 148 | + assertThrows(JSQLParserException.class, |
| 149 | + () -> parse("CREATE TABLE t (n integer, d date) PARTITION BY RANGE (" |
| 150 | + + expression + ")")); |
| 151 | + roundTrip(checked("CREATE INDEX ix ON t ((" + expression + "))")); |
| 152 | + roundTrip(checked("CREATE TABLE t (n integer, d date) PARTITION BY RANGE ((" |
| 153 | + + expression + "))")); |
| 154 | + } |
| 155 | + |
| 156 | + @ParameterizedTest |
| 157 | + @ValueSource(strings = {"MODULUS 8, REMAINDER 3", "REMAINDER 3, MODULUS 8"}) |
| 158 | + void hashBoundsKeepTheirNamedValuesInEitherOrder(String options) throws JSQLParserException { |
| 159 | + for (Dialect dialect : new Dialect[] {null, Dialect.POSTGRESQL}) { |
| 160 | + for (boolean attach : new boolean[] {false, true}) { |
| 161 | + String prefix = attach ? "ALTER TABLE parent ATTACH PARTITION child " |
| 162 | + : "CREATE TABLE child PARTITION OF parent "; |
| 163 | + Statement statement = parse(prefix + "FOR VALUES WITH (" + options + ")", dialect); |
| 164 | + PartitionBound bound = attach |
| 165 | + ? ((AlterExpressionPartition) ((Alter) statement).getAlterExpressions() |
| 166 | + .get(0)) |
| 167 | + .getPartitionBound() |
| 168 | + : ((CreateTable) statement).getPartitionBound(); |
| 169 | + assertEquals(PartitionBound.Type.HASH, bound.getType()); |
| 170 | + assertEquals(8, assertInstanceOf(LongValue.class, bound.getModulus()).getValue()); |
| 171 | + assertEquals(3, assertInstanceOf(LongValue.class, bound.getRemainder()).getValue()); |
| 172 | + assertEquals(prefix + "FOR VALUES WITH (MODULUS 8, REMAINDER 3)", |
| 173 | + statement.toString()); |
| 174 | + roundTrip(statement, dialect); |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + @ParameterizedTest |
| 180 | + @ValueSource(strings = {"MODULUS 8", "REMAINDER 3", "MODULUS 8, MODULUS 8", |
| 181 | + "REMAINDER 3, REMAINDER 3", "MODULUS 8, REMAINDER 3, MODULUS 8", |
| 182 | + "REMAINDER 3, MODULUS 8, REMAINDER 3"}) |
| 183 | + void rejectsMissingAndDuplicateHashBoundOptions(String options) { |
| 184 | + for (String prefix : new String[] {"CREATE TABLE child PARTITION OF parent ", |
| 185 | + "ALTER TABLE parent ATTACH PARTITION child "}) { |
| 186 | + assertThrows(JSQLParserException.class, |
| 187 | + () -> parse(prefix + "FOR VALUES WITH (" + options + ")")); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + @ParameterizedTest |
| 192 | + @ValueSource(strings = {"LOGGED", "UNLOGGED"}) |
| 193 | + void identityPersistenceIsAnOptionForCreateAndAdd(String persistence) |
| 194 | + throws JSQLParserException { |
| 195 | + String definition = "GENERATED ALWAYS AS IDENTITY (SEQUENCE NAME public.ids " |
| 196 | + + persistence + " START WITH 10 INCREMENT BY 3)"; |
| 197 | + CreateTable table = (CreateTable) checked("CREATE TABLE t (id bigint " + definition + ")"); |
| 198 | + Alter alter = (Alter) checked("ALTER TABLE t ALTER COLUMN id ADD " + definition); |
| 199 | + IdentityDefinition created = table.getColumnDefinitions().get(0).getColumnOptions().get(0) |
| 200 | + .getIdentityDefinition(); |
| 201 | + IdentityDefinition added = alter.getAlterExpressions().get(0).getColDataTypeList().get(0) |
| 202 | + .getIdentityAlterations().get(0).getIdentityDefinition(); |
| 203 | + for (IdentityDefinition identity : new IdentityDefinition[] {created, added}) { |
| 204 | + assertEquals(IdentityDefinition.GenerationMode.ALWAYS, identity.getGenerationMode()); |
| 205 | + assertEquals(4, identity.getParameters().size()); |
| 206 | + Sequence.Parameter option = identity.getParameters().get(1); |
| 207 | + assertEquals(persistence, option.getOption().name()); |
| 208 | + assertNull(option.getValue()); |
| 209 | + assertNull(option.getSequenceName()); |
| 210 | + assertEquals("public.ids", identity.getParameters().get(0).getSequenceName() |
| 211 | + .getFullyQualifiedName()); |
| 212 | + assertEquals(10L, identity.getParameters().get(2).getValue()); |
| 213 | + assertEquals(3L, identity.getParameters().get(3).getValue()); |
| 214 | + } |
| 215 | + assertFalse(table.isUnlogged()); |
| 216 | + roundTrip(table); |
| 217 | + roundTrip(alter); |
| 218 | + FeatureConfiguration configuration = new FeatureConfiguration() |
| 219 | + .setValue(Feature.dialect, Dialect.POSTGRESQL.name()); |
| 220 | + assertTrue(new Validation(configuration, List.of(FeaturesAllowed.DDL), table.toString(), |
| 221 | + alter.toString()).validate().isEmpty()); |
| 222 | + } |
| 223 | + |
| 224 | + @ParameterizedTest |
| 225 | + @ValueSource(strings = {"LOGGED UNLOGGED", "UNLOGGED LOGGED", "LOGGED LOGGED", |
| 226 | + "UNLOGGED UNLOGGED", "LOGGED 1", "UNLOGGED 1"}) |
| 227 | + void rejectsConflictingAndMalformedIdentityPersistence(String options) { |
| 228 | + for (String sql : new String[] { |
| 229 | + "CREATE TABLE t (id bigint GENERATED ALWAYS AS IDENTITY (" + options + "))", |
| 230 | + "ALTER TABLE t ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (" + options |
| 231 | + + ")"}) { |
| 232 | + assertThrows(JSQLParserException.class, () -> parse(sql), sql); |
| 233 | + } |
| 234 | + } |
| 235 | + |
| 236 | + @Test |
| 237 | + void identityOptionsDoNotChangeStandaloneSequenceGrammar() { |
| 238 | + for (String sql : new String[] {"CREATE SEQUENCE ids LOGGED", |
| 239 | + "CREATE SEQUENCE ids UNLOGGED", "ALTER SEQUENCE ids LOGGED", |
| 240 | + "ALTER SEQUENCE ids UNLOGGED"}) { |
| 241 | + assertThrows(JSQLParserException.class, () -> parse(sql), sql); |
| 242 | + } |
| 243 | + } |
| 244 | + |
| 245 | + private static List<String> visitedColumns(Statement statement) { |
| 246 | + List<String> columns = new ArrayList<>(); |
| 247 | + ExpressionVisitorAdapter<Void> expressions = new ExpressionVisitorAdapter<Void>() { |
| 248 | + @Override |
| 249 | + public <S> Void visit(Column column, S context) { |
| 250 | + assertEquals("context", context); |
| 251 | + columns.add(column.getColumnName()); |
| 252 | + return null; |
| 253 | + } |
| 254 | + }; |
| 255 | + statement.accept(new StatementVisitorAdapter<>(new SelectVisitorAdapter<>(expressions)), |
| 256 | + "context"); |
| 257 | + return columns; |
| 258 | + } |
| 259 | + |
| 260 | + private static Statement checked(String sql) throws JSQLParserException { |
| 261 | + return assertSqlCanBeParsedAndDeparsed(sql, false, |
| 262 | + parser -> parser.withDialect(Dialect.POSTGRESQL)); |
| 263 | + } |
| 264 | + |
| 265 | + private static Statement parse(String sql) throws JSQLParserException { |
| 266 | + return parse(sql, Dialect.POSTGRESQL); |
| 267 | + } |
| 268 | + |
| 269 | + private static Statement parse(String sql, Dialect dialect) throws JSQLParserException { |
| 270 | + return CCJSqlParserUtil.parse(sql, parser -> { |
| 271 | + if (dialect != null) { |
| 272 | + parser.withDialect(dialect); |
| 273 | + } |
| 274 | + }); |
| 275 | + } |
| 276 | + |
| 277 | + private static void roundTrip(Statement statement) throws JSQLParserException { |
| 278 | + roundTrip(statement, Dialect.POSTGRESQL); |
| 279 | + } |
| 280 | + |
| 281 | + private static void roundTrip(Statement statement, Dialect dialect) throws JSQLParserException { |
| 282 | + StringBuilder output = new StringBuilder(); |
| 283 | + statement.accept(new StatementDeParser(output)); |
| 284 | + assertEquals(statement.toString(), output.toString()); |
| 285 | + assertEquals(output.toString(), parse(output.toString(), dialect).toString()); |
| 286 | + } |
| 287 | +} |
0 commit comments