-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
H2LegacySqlAstTranslator.java
414 lines (368 loc) · 13.7 KB
/
H2LegacySqlAstTranslator.java
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
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.community.dialect;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.dialect.identity.H2IdentityColumnSupport;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.collections.Stack;
import org.hibernate.query.IllegalQueryOperationException;
import org.hibernate.query.sqm.ComparisonOperator;
import org.hibernate.sql.ast.Clause;
import org.hibernate.sql.ast.SqlAstNodeRenderingMode;
import org.hibernate.sql.ast.spi.AbstractSqlAstTranslator;
import org.hibernate.sql.ast.spi.SqlSelection;
import org.hibernate.sql.ast.tree.Statement;
import org.hibernate.sql.ast.tree.cte.CteContainer;
import org.hibernate.sql.ast.tree.cte.CteTableGroup;
import org.hibernate.sql.ast.tree.delete.DeleteStatement;
import org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression;
import org.hibernate.sql.ast.tree.expression.ColumnReference;
import org.hibernate.sql.ast.tree.expression.Expression;
import org.hibernate.sql.ast.tree.expression.Literal;
import org.hibernate.sql.ast.tree.expression.SqlTuple;
import org.hibernate.sql.ast.tree.expression.SqlTupleContainer;
import org.hibernate.sql.ast.tree.expression.Summarization;
import org.hibernate.sql.ast.tree.from.NamedTableReference;
import org.hibernate.sql.ast.tree.from.QueryPartTableReference;
import org.hibernate.sql.ast.tree.from.TableGroup;
import org.hibernate.sql.ast.tree.from.TableReference;
import org.hibernate.sql.ast.tree.insert.ConflictClause;
import org.hibernate.sql.ast.tree.insert.InsertSelectStatement;
import org.hibernate.sql.ast.tree.predicate.BooleanExpressionPredicate;
import org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate;
import org.hibernate.sql.ast.tree.predicate.LikePredicate;
import org.hibernate.sql.ast.tree.select.QueryPart;
import org.hibernate.sql.ast.tree.select.SelectClause;
import org.hibernate.sql.ast.tree.update.UpdateStatement;
import org.hibernate.sql.exec.spi.JdbcOperation;
import org.hibernate.sql.model.internal.TableInsertStandard;
import org.hibernate.sql.model.internal.TableUpdateStandard;
import static org.hibernate.internal.util.collections.CollectionHelper.isEmpty;
/**
* A legacy SQL AST translator for H2.
*
* @author Christian Beikov
*/
public class H2LegacySqlAstTranslator<T extends JdbcOperation> extends AbstractSqlAstTranslator<T> {
private boolean renderAsArray;
public H2LegacySqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement) {
super( sessionFactory, statement );
}
@Override
public void visitStandardTableInsert(TableInsertStandard tableInsert) {
if ( getDialect().getVersion().isSameOrAfter( 2 )
|| CollectionHelper.isEmpty( tableInsert.getReturningColumns() ) ) {
final boolean closeWrapper = renderReturningClause( tableInsert.getReturningColumns() );
super.visitStandardTableInsert( tableInsert );
if ( closeWrapper ) {
appendSql( ')' );
}
}
else {
visitReturningInsertStatement( tableInsert );
}
}
@Override
public void visitStandardTableUpdate(TableUpdateStandard tableUpdate) {
final boolean closeWrapper = renderReturningClause( tableUpdate.getReturningColumns() );
super.visitStandardTableUpdate( tableUpdate );
if ( closeWrapper ) {
appendSql( ')' );
}
}
protected boolean renderReturningClause(List<ColumnReference> returningColumns) {
if ( isEmpty( returningColumns ) ) {
return false;
}
appendSql( "select " );
for ( int i = 0; i < returningColumns.size(); i++ ) {
if ( i > 0 ) {
appendSql( ", " );
}
appendSql( returningColumns.get( i ).getColumnExpression() );
}
appendSql( " from final table (" );
return true;
}
@Override
protected void visitReturningColumns(List<ColumnReference> returningColumns) {
// do nothing - this is handled via `#renderReturningClause`
}
public void visitReturningInsertStatement(TableInsertStandard tableInsert) {
assert tableInsert.getReturningColumns() != null
&& !tableInsert.getReturningColumns().isEmpty();
final H2IdentityColumnSupport identitySupport = (H2IdentityColumnSupport) getSessionFactory()
.getJdbcServices()
.getDialect()
.getIdentityColumnSupport();
identitySupport.render(
tableInsert,
this::appendSql,
(columnReference) -> columnReference.accept( this ),
() -> super.visitStandardTableInsert( tableInsert ),
getSessionFactory()
);
}
@Override
protected void visitInsertStatementOnly(InsertSelectStatement statement) {
if ( statement.getConflictClause() == null || statement.getConflictClause().isDoNothing() ) {
// Render plain insert statement and possibly run into unique constraint violation
super.visitInsertStatementOnly( statement );
}
else {
visitInsertStatementEmulateMerge( statement );
}
}
@Override
protected void visitDeleteStatementOnly(DeleteStatement statement) {
if ( hasNonTrivialFromClause( statement.getFromClause() ) ) {
appendSql( "delete from " );
final Stack<Clause> clauseStack = getClauseStack();
try {
clauseStack.push( Clause.DELETE );
super.renderDmlTargetTableExpression( statement.getTargetTable() );
append( " dml_target_" );
}
finally {
clauseStack.pop();
}
visitWhereClause( determineWhereClauseRestrictionWithJoinEmulation( statement, "dml_target_" ) );
visitReturningColumns( statement.getReturningColumns() );
}
else {
super.visitDeleteStatementOnly( statement );
}
}
@Override
protected void visitUpdateStatementOnly(UpdateStatement statement) {
if ( hasNonTrivialFromClause( statement.getFromClause() ) ) {
visitUpdateStatementEmulateMerge( statement );
}
else {
super.visitUpdateStatementOnly( statement );
}
}
@Override
protected void renderDmlTargetTableExpression(NamedTableReference tableReference) {
super.renderDmlTargetTableExpression( tableReference );
if ( getClauseStack().getCurrent() != Clause.INSERT ) {
renderTableReferenceIdentificationVariable( tableReference );
}
}
@Override
protected void visitConflictClause(ConflictClause conflictClause) {
if ( conflictClause != null ) {
if ( conflictClause.isDoUpdate() && conflictClause.getConstraintName() != null ) {
throw new IllegalQueryOperationException( "Insert conflict 'do update' clause with constraint name is not supported" );
}
}
}
@Override
public void visitCteContainer(CteContainer cteContainer) {
// H2 has various bugs in different versions that make it impossible to use CTEs with parameters reliably
withParameterRenderingMode(
SqlAstNodeRenderingMode.INLINE_PARAMETERS,
() -> super.visitCteContainer( cteContainer )
);
}
@Override
protected boolean needsCteInlining() {
// CTEs in H2 are just so buggy, that we can't reliably use them
return true;
}
@Override
protected boolean shouldInlineCte(TableGroup tableGroup) {
return tableGroup instanceof CteTableGroup
&& !getCteStatement( tableGroup.getPrimaryTableReference().getTableId() ).isRecursive();
}
@Override
protected boolean supportsWithClauseInSubquery() {
return false;
}
@Override
protected boolean supportsRowConstructor() {
return getDialect().getVersion().isSameOrAfter( 2 );
}
@Override
protected boolean supportsArrayConstructor() {
return getDialect().getVersion().isSameOrAfter( 2 );
}
@Override
protected String getArrayContainsFunction() {
return "array_contains";
}
@Override
protected void renderExpressionAsClauseItem(Expression expression) {
expression.accept( this );
}
@Override
public void visitBooleanExpressionPredicate(BooleanExpressionPredicate booleanExpressionPredicate) {
final boolean isNegated = booleanExpressionPredicate.isNegated();
if ( isNegated ) {
appendSql( "not(" );
}
booleanExpressionPredicate.getExpression().accept( this );
if ( isNegated ) {
appendSql( CLOSE_PARENTHESIS );
}
}
@Override
public void visitOffsetFetchClause(QueryPart queryPart) {
if ( isRowsOnlyFetchClauseType( queryPart ) ) {
if ( supportsOffsetFetchClause() ) {
renderOffsetFetchClause( queryPart, true );
}
else {
renderLimitOffsetClause( queryPart );
}
}
else {
if ( supportsOffsetFetchClausePercentWithTies() ) {
renderOffsetFetchClause( queryPart, true );
}
else {
// FETCH PERCENT and WITH TIES were introduced along with window functions
throw new IllegalArgumentException( "Can't emulate fetch clause type: " + queryPart.getFetchClauseType() );
}
}
}
@Override
protected void renderSelectTupleComparison(
List<SqlSelection> lhsExpressions,
SqlTuple tuple,
ComparisonOperator operator) {
emulateSelectTupleComparison( lhsExpressions, tuple.getExpressions(), operator, true );
}
@Override
public void visitInSubQueryPredicate(InSubQueryPredicate inSubQueryPredicate) {
final SqlTuple lhsTuple;
// As of 1.4.200 this is supported
if ( getDialect().getVersion().isBefore( 1, 4, 200 )
&& ( lhsTuple = SqlTupleContainer.getSqlTuple( inSubQueryPredicate.getTestExpression() ) ) != null
&& lhsTuple.getExpressions().size() != 1 ) {
inSubQueryPredicate.getTestExpression().accept( this );
if ( inSubQueryPredicate.isNegated() ) {
appendSql( " not" );
}
appendSql( " in" );
final boolean renderAsArray = this.renderAsArray;
this.renderAsArray = true;
inSubQueryPredicate.getSubQuery().accept( this );
this.renderAsArray = renderAsArray;
}
else {
super.visitInSubQueryPredicate( inSubQueryPredicate );
}
}
@Override
protected void visitSqlSelections(SelectClause selectClause) {
final boolean renderAsArray = this.renderAsArray;
this.renderAsArray = false;
if ( renderAsArray ) {
append( OPEN_PARENTHESIS );
}
super.visitSqlSelections( selectClause );
if ( renderAsArray ) {
append( CLOSE_PARENTHESIS );
}
}
@Override
protected void renderPartitionItem(Expression expression) {
if ( expression instanceof Literal ) {
appendSql( "'0' || '0'" );
}
else if ( expression instanceof Summarization ) {
// This could theoretically be emulated by rendering all grouping variations of the query and
// connect them via union all but that's probably pretty inefficient and would have to happen
// on the query spec level
throw new UnsupportedOperationException( "Summarization is not supported by DBMS" );
}
else {
expression.accept( this );
}
}
@Override
public void visitBinaryArithmeticExpression(BinaryArithmeticExpression arithmeticExpression) {
appendSql( OPEN_PARENTHESIS );
visitArithmeticOperand( arithmeticExpression.getLeftHandOperand() );
appendSql( arithmeticExpression.getOperator().getOperatorSqlTextString() );
visitArithmeticOperand( arithmeticExpression.getRightHandOperand() );
appendSql( CLOSE_PARENTHESIS );
}
@Override
protected void visitArithmeticOperand(Expression expression) {
render( expression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER );
}
@Override
protected boolean renderPrimaryTableReference(TableGroup tableGroup, LockMode lockMode) {
final TableReference tableRef = tableGroup.getPrimaryTableReference();
// The H2 parser can't handle a sub-query as first element in a nested join
// i.e. `join ( (select ...) alias join ... )`, so we have to introduce a dummy table reference
if ( tableRef instanceof QueryPartTableReference || tableRef.getTableId().startsWith( "(select" ) ) {
final boolean realTableGroup = tableGroup.isRealTableGroup()
&& ( CollectionHelper.isNotEmpty( tableGroup.getTableReferenceJoins() )
|| hasNestedTableGroupsToRender( tableGroup.getNestedTableGroupJoins() ) );
if ( realTableGroup ) {
appendSql( "dual cross join " );
}
}
return super.renderPrimaryTableReference( tableGroup, lockMode );
}
@Override
public void visitLikePredicate(LikePredicate likePredicate) {
super.visitLikePredicate( likePredicate );
// Custom implementation because H2 uses backslash as the default escape character
// We can override this by specifying an empty escape character
// See http://www.h2database.com/html/grammar.html#like_predicate_right_hand_side
if ( likePredicate.getEscapeCharacter() == null ) {
appendSql( " escape ''" );
}
}
@Override
protected boolean supportsRowValueConstructorSyntax() {
// Just a guess
return getDialect().getVersion().isSameOrAfter( 1, 4, 197 );
}
@Override
protected boolean supportsRowValueConstructorSyntaxInInList() {
// Just a guess
return getDialect().getVersion().isSameOrAfter( 1, 4, 197 );
}
@Override
protected boolean supportsRowValueConstructorSyntaxInQuantifiedPredicates() {
// Just a guess
return getDialect().getVersion().isSameOrAfter( 1, 4, 197 );
}
@Override
protected boolean supportsRowValueConstructorDistinctFromSyntax() {
// Seems that before, this was buggy
return getDialect().getVersion().isSameOrAfter( 1, 4, 200 );
}
@Override
protected boolean supportsNullPrecedence() {
// Support for nulls clause in listagg was added in 2.0
return getClauseStack().getCurrent() != Clause.WITHIN_GROUP || getDialect().getVersion().isSameOrAfter( 2 );
}
@Override
protected String getDual() {
return "dual";
}
private boolean supportsOffsetFetchClause() {
return getDialect().getVersion().isSameOrAfter( 1, 4, 195 );
}
private boolean supportsOffsetFetchClausePercentWithTies() {
// Introduction of TIES clause https://github.com/h2database/h2database/commit/876e9fbe7baf11d01675bfe871aac2cf1b6104ce
// Introduction of PERCENT support https://github.com/h2database/h2database/commit/f45913302e5f6ad149155a73763c0c59d8205849
return getDialect().getVersion().isSameOrAfter( 1, 4, 198 );
}
@Override
protected boolean supportsJoinInMutationStatementSubquery() {
return false;
}
}