-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
SqlDialect.java
1600 lines (1479 loc) · 57.3 KB
/
SqlDialect.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
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.sql;
import org.apache.calcite.avatica.util.Casing;
import org.apache.calcite.avatica.util.Quoting;
import org.apache.calcite.avatica.util.TimeUnit;
import org.apache.calcite.config.NullCollation;
import org.apache.calcite.linq4j.function.Experimental;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeSystem;
import org.apache.calcite.rel.type.RelDataTypeSystemImpl;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.dialect.JethroDataSqlDialect;
import org.apache.calcite.sql.fun.SqlInternalOperators;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.AbstractSqlType;
import org.apache.calcite.sql.type.SqlTypeUtil;
import org.apache.calcite.sql.validate.SqlConformance;
import org.apache.calcite.sql.validate.SqlConformanceEnum;
import com.google.common.base.Preconditions;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.dataflow.qual.Pure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import static org.apache.calcite.util.DateTimeStringUtils.getDateFormatter;
/**
* <code>SqlDialect</code> encapsulates the differences between dialects of SQL.
*
* <p>It is used by classes such as {@link SqlWriter} and
* {@link org.apache.calcite.sql.util.SqlBuilder}.
*
* <p>To add a new {@link SqlDialect} sub-class, extends this class to hold 2 public final
* static member:
* <ul>
* <li>DEFAULT_CONTEXT: a default {@link Context} instance, which can be used to customize
* or extending the dialect if the DEFAULT instance does not meet the requests</li>
* <li>DEFAULT: the default {@link SqlDialect} instance with context properties defined with
* <code>DEFAULT_CONTEXT</code></li>
* </ul>
*/
public class SqlDialect {
//~ Static fields/initializers ---------------------------------------------
protected static final Logger LOGGER =
LoggerFactory.getLogger(SqlDialect.class);
/** Empty context. */
public static final Context EMPTY_CONTEXT = emptyContext();
/** Built-in scalar functions and operators common for every dialect. */
protected static final Set<SqlOperator> BUILT_IN_OPERATORS_LIST =
ImmutableSet.<SqlOperator>builder()
.add(SqlStdOperatorTable.ABS)
.add(SqlStdOperatorTable.ACOS)
.add(SqlStdOperatorTable.AND)
.add(SqlStdOperatorTable.ASIN)
.add(SqlStdOperatorTable.BETWEEN)
.add(SqlStdOperatorTable.CASE)
.add(SqlStdOperatorTable.CAST)
.add(SqlStdOperatorTable.CEIL)
.add(SqlStdOperatorTable.CHAR_LENGTH)
.add(SqlStdOperatorTable.CHARACTER_LENGTH)
.add(SqlStdOperatorTable.COALESCE)
.add(SqlStdOperatorTable.CONCAT)
.add(SqlStdOperatorTable.CBRT)
.add(SqlStdOperatorTable.COS)
.add(SqlStdOperatorTable.COT)
.add(SqlStdOperatorTable.DIVIDE)
.add(SqlStdOperatorTable.EQUALS)
.add(SqlStdOperatorTable.FLOOR)
.add(SqlStdOperatorTable.GREATER_THAN)
.add(SqlStdOperatorTable.GREATER_THAN_OR_EQUAL)
.add(SqlStdOperatorTable.IN)
.add(SqlStdOperatorTable.IS_NOT_NULL)
.add(SqlStdOperatorTable.IS_NULL)
.add(SqlStdOperatorTable.LESS_THAN)
.add(SqlStdOperatorTable.LESS_THAN_OR_EQUAL)
.add(SqlStdOperatorTable.LIKE)
.add(SqlStdOperatorTable.LN)
.add(SqlStdOperatorTable.LOG10)
.add(SqlStdOperatorTable.MINUS)
.add(SqlStdOperatorTable.MOD)
.add(SqlStdOperatorTable.MULTIPLY)
.add(SqlStdOperatorTable.NOT)
.add(SqlStdOperatorTable.NOT_BETWEEN)
.add(SqlStdOperatorTable.NOT_EQUALS)
.add(SqlStdOperatorTable.NOT_IN)
.add(SqlStdOperatorTable.NOT_LIKE)
.add(SqlStdOperatorTable.OR)
.add(SqlStdOperatorTable.PI)
.add(SqlStdOperatorTable.PLUS)
.add(SqlStdOperatorTable.POWER)
.add(SqlStdOperatorTable.RAND)
.add(SqlStdOperatorTable.ROUND)
.add(SqlStdOperatorTable.ROW)
.add(SqlStdOperatorTable.SIN)
.add(SqlStdOperatorTable.SQRT)
.add(SqlStdOperatorTable.SUBSTRING)
.add(SqlStdOperatorTable.TAN)
.build();
//~ Instance fields --------------------------------------------------------
protected final @Nullable String identifierQuoteString;
protected final @Nullable String identifierEndQuoteString;
protected final @Nullable String identifierEscapedQuote;
protected final String literalQuoteString;
protected final String literalEndQuoteString;
protected final String literalEscapedQuote;
private final DatabaseProduct databaseProduct;
protected final NullCollation nullCollation;
private final RelDataTypeSystem dataTypeSystem;
private final Casing unquotedCasing;
private final Casing quotedCasing;
private final boolean caseSensitive;
//~ Constructors -----------------------------------------------------------
/**
* Creates a <code>SqlDialect</code> from a DatabaseMetaData.
*
* <p>Does not maintain a reference to the DatabaseMetaData -- or, more
* importantly, to its {@link java.sql.Connection} -- after this call has
* returned.
*
* @param databaseMetaData used to determine which dialect of SQL to generate
*
* @deprecated Replaced by {@link SqlDialectFactory}
*/
@Deprecated // to be removed before 2.0
public static SqlDialect create(DatabaseMetaData databaseMetaData) {
return new SqlDialectFactoryImpl().create(databaseMetaData);
}
@Deprecated // to be removed before 2.0
public SqlDialect(DatabaseProduct databaseProduct, String databaseProductName,
String identifierQuoteString) {
this(EMPTY_CONTEXT
.withDatabaseProduct(databaseProduct)
.withDatabaseProductName(databaseProductName)
.withIdentifierQuoteString(identifierQuoteString));
}
/**
* Creates a SqlDialect.
*
* @param databaseProduct Database product; may be UNKNOWN, never null
* @param databaseProductName Database product name from JDBC driver
* @param identifierQuoteString String to quote identifiers. Null if quoting
* is not supported. If "[", close quote is
* deemed to be "]".
* @param nullCollation Whether NULL values appear first or last
*
* @deprecated Use {@link #SqlDialect(Context)}
*/
@Deprecated // to be removed before 2.0
public SqlDialect(DatabaseProduct databaseProduct, String databaseProductName,
String identifierQuoteString, NullCollation nullCollation) {
this(EMPTY_CONTEXT
.withDatabaseProduct(databaseProduct)
.withDatabaseProductName(databaseProductName)
.withIdentifierQuoteString(identifierQuoteString)
.withNullCollation(nullCollation));
}
/**
* Creates a SqlDialect.
*
* @param context All the information necessary to create a dialect
*/
public SqlDialect(Context context) {
this.nullCollation = Objects.requireNonNull(context.nullCollation());
this.dataTypeSystem = Objects.requireNonNull(context.dataTypeSystem());
this.databaseProduct =
Objects.requireNonNull(context.databaseProduct());
this.literalQuoteString =
Objects.requireNonNull(context.literalQuoteString());
this.literalEndQuoteString =
Objects.requireNonNull(context.literalQuoteString());
this.literalEscapedQuote =
Objects.requireNonNull(context.literalEscapedQuoteString());
String identifierQuoteString = context.identifierQuoteString();
if (identifierQuoteString != null) {
identifierQuoteString = identifierQuoteString.trim();
if (identifierQuoteString.equals("")) {
identifierQuoteString = null;
}
}
this.identifierQuoteString = identifierQuoteString;
this.identifierEndQuoteString =
identifierQuoteString == null ? null
: identifierQuoteString.equals("[") ? "]"
: identifierQuoteString;
this.identifierEscapedQuote =
identifierQuoteString == null ? null
: this.identifierEndQuoteString + this.identifierEndQuoteString;
this.unquotedCasing = Objects.requireNonNull(context.unquotedCasing());
this.quotedCasing = Objects.requireNonNull(context.quotedCasing());
this.caseSensitive = context.caseSensitive();
}
//~ Methods ----------------------------------------------------------------
/** Creates an empty context. Use {@link #EMPTY_CONTEXT} to reference the instance. */
private static Context emptyContext() {
return new ContextImpl(DatabaseProduct.UNKNOWN, null, null, -1, -1,
"'", "''", null,
Casing.UNCHANGED, Casing.TO_UPPER, true, SqlConformanceEnum.DEFAULT,
NullCollation.HIGH, RelDataTypeSystemImpl.DEFAULT,
JethroDataSqlDialect.JethroInfo.EMPTY);
}
/**
* Converts a product name and version (per the JDBC driver) into a product
* enumeration.
*
* @param productName Product name
* @param productVersion Product version
* @return database product
*/
@Deprecated // to be removed before 2.0
public static DatabaseProduct getProduct(
String productName,
String productVersion) {
final String upperProductName =
productName.toUpperCase(Locale.ROOT).trim();
switch (upperProductName) {
case "ACCESS":
return DatabaseProduct.ACCESS;
case "APACHE DERBY":
return DatabaseProduct.DERBY;
case "CLICKHOUSE":
return DatabaseProduct.CLICKHOUSE;
case "DBMS:CLOUDSCAPE":
return DatabaseProduct.DERBY;
case "HIVE":
return DatabaseProduct.HIVE;
case "INGRES":
return DatabaseProduct.INGRES;
case "INTERBASE":
return DatabaseProduct.INTERBASE;
case "LUCIDDB":
return DatabaseProduct.LUCIDDB;
case "ORACLE":
return DatabaseProduct.ORACLE;
case "PHOENIX":
return DatabaseProduct.PHOENIX;
case "PRESTO":
return DatabaseProduct.PRESTO;
case "MYSQL (INFOBRIGHT)":
return DatabaseProduct.INFOBRIGHT;
case "MYSQL":
return DatabaseProduct.MYSQL;
case "REDSHIFT":
return DatabaseProduct.REDSHIFT;
default:
break;
}
// Now the fuzzy matches.
if (productName.startsWith("DB2")) {
return DatabaseProduct.DB2;
} else if (upperProductName.contains("FIREBIRD")) {
return DatabaseProduct.FIREBIRD;
} else if (productName.startsWith("Informix")) {
return DatabaseProduct.INFORMIX;
} else if (upperProductName.contains("NETEZZA")) {
return DatabaseProduct.NETEZZA;
} else if (upperProductName.contains("PARACCEL")) {
return DatabaseProduct.PARACCEL;
} else if (productName.startsWith("HP Neoview")) {
return DatabaseProduct.NEOVIEW;
} else if (upperProductName.contains("POSTGRE")) {
return DatabaseProduct.POSTGRESQL;
} else if (upperProductName.contains("SQL SERVER")) {
return DatabaseProduct.MSSQL;
} else if (upperProductName.contains("SYBASE")) {
return DatabaseProduct.SYBASE;
} else if (upperProductName.contains("TERADATA")) {
return DatabaseProduct.TERADATA;
} else if (upperProductName.contains("HSQL")) {
return DatabaseProduct.HSQLDB;
} else if (upperProductName.contains("H2")) {
return DatabaseProduct.H2;
} else if (upperProductName.contains("VERTICA")) {
return DatabaseProduct.VERTICA;
} else if (upperProductName.contains("GOOGLE BIGQUERY")) {
return DatabaseProduct.BIG_QUERY;
} else {
return DatabaseProduct.UNKNOWN;
}
}
/** Returns the type system implementation for this dialect. */
public RelDataTypeSystem getTypeSystem() {
return dataTypeSystem;
}
/**
* Encloses an identifier in quotation marks appropriate for the current SQL
* dialect.
*
* <p>For example, <code>quoteIdentifier("emp")</code> yields a string
* containing <code>"emp"</code> in Oracle, and a string containing <code>
* [emp]</code> in Access.
*
* @param val Identifier to quote
* @return Quoted identifier
*/
public String quoteIdentifier(String val) {
return quoteIdentifier(new StringBuilder(), val).toString();
}
/**
* Encloses an identifier in quotation marks appropriate for the current SQL
* dialect, writing the result to a {@link StringBuilder}.
*
* <p>For example, <code>quoteIdentifier("emp")</code> yields a string
* containing <code>"emp"</code> in Oracle, and a string containing <code>
* [emp]</code> in Access.
*
* @param buf Buffer
* @param val Identifier to quote
* @return The buffer
*/
public StringBuilder quoteIdentifier(
StringBuilder buf,
String val) {
if (identifierQuoteString == null // quoting is not supported
|| identifierEndQuoteString == null
|| identifierEscapedQuote == null
|| !identifierNeedsQuote(val)) {
buf.append(val);
} else {
buf.append(identifierQuoteString);
buf.append(val.replace(identifierEndQuoteString, identifierEscapedQuote));
buf.append(identifierEndQuoteString);
}
return buf;
}
/**
* Quotes a multi-part identifier.
*
* @param buf Buffer
* @param identifiers List of parts of the identifier to quote
* @return The buffer
*/
public StringBuilder quoteIdentifier(
StringBuilder buf,
List<String> identifiers) {
int i = 0;
for (String identifier : identifiers) {
if (i++ > 0) {
buf.append('.');
}
quoteIdentifier(buf, identifier);
}
return buf;
}
/** Returns whether to quote an identifier.
* By default, all identifiers are quoted. */
protected boolean identifierNeedsQuote(String val) {
return true;
}
/**
* Converts a string into a string literal.
*
* <p>For example, {@code "can't run"} becomes {@code "'can''t run'"}.
*/
public final String quoteStringLiteral(String val) {
final StringBuilder buf = new StringBuilder();
quoteStringLiteral(buf, null, val);
return buf.toString();
}
/** Appends a string literal to a buffer.
*
* @param buf Buffer
* @param charsetName Character set name, e.g. "utf16", or null
* @param val String value
*/
public void quoteStringLiteral(StringBuilder buf, @Nullable String charsetName,
String val) {
if (containsNonAscii(val) && charsetName == null) {
quoteStringLiteralUnicode(buf, val);
} else {
if (charsetName != null) {
buf.append("_");
buf.append(charsetName);
}
buf.append(literalQuoteString);
buf.append(val.replace(literalEndQuoteString, literalEscapedQuote));
buf.append(literalEndQuoteString);
}
}
public void unparseCall(SqlWriter writer, SqlCall call, int leftPrec,
int rightPrec) {
SqlOperator operator = call.getOperator();
switch (call.getKind()) {
case ROW:
// Remove the ROW keyword if the dialect does not allow that.
if (!getConformance().allowExplicitRowValueConstructor()) {
if (writer.isAlwaysUseParentheses()) {
// If writer always uses parentheses, it will have started parentheses
// that we now regret. Use a special variant of the operator that does
// not print parentheses, so that we can use the ones already started.
operator = SqlInternalOperators.ANONYMOUS_ROW_NO_PARENTHESES;
} else {
// Use an operator that prints "(a, b, c)" rather than
// "ROW (a, b, c)".
operator = SqlInternalOperators.ANONYMOUS_ROW;
}
}
// fall through
default:
operator.unparse(writer, call, leftPrec, rightPrec);
}
}
public void unparseDateTimeLiteral(SqlWriter writer,
SqlAbstractDateTimeLiteral literal, int leftPrec, int rightPrec) {
writer.literal(literal.toString());
}
public void unparseSqlDatetimeArithmetic(SqlWriter writer,
SqlCall call, SqlKind sqlKind, int leftPrec, int rightPrec) {
final SqlWriter.Frame frame = writer.startList("(", ")");
call.operand(0).unparse(writer, leftPrec, rightPrec);
writer.sep((SqlKind.PLUS == sqlKind) ? "+" : "-");
call.operand(1).unparse(writer, leftPrec, rightPrec);
writer.endList(frame);
//Only two parameters are present normally
//Checking parameter count to prevent errors
if (call.getOperandList().size() > 2) {
call.operand(2).unparse(writer, leftPrec, rightPrec);
}
}
/** Converts an interval qualifier to a SQL string. The default implementation
* returns strings such as
* <code>INTERVAL '1 2:3:4' DAY(4) TO SECOND(4)</code>. */
public void unparseSqlIntervalQualifier(SqlWriter writer,
SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {
final String start = qualifier.timeUnitRange.startUnit.name();
final int fractionalSecondPrecision =
qualifier.getFractionalSecondPrecision(typeSystem);
final int startPrecision = qualifier.getStartPrecision(typeSystem);
if (qualifier.timeUnitRange.startUnit == TimeUnit.SECOND) {
if (!qualifier.useDefaultFractionalSecondPrecision()) {
final SqlWriter.Frame frame = writer.startFunCall(start);
writer.print(startPrecision);
writer.sep(",", true);
writer.print(qualifier.getFractionalSecondPrecision(typeSystem));
writer.endList(frame);
} else if (!qualifier.useDefaultStartPrecision()) {
final SqlWriter.Frame frame = writer.startFunCall(start);
writer.print(startPrecision);
writer.endList(frame);
} else {
writer.keyword(start);
}
} else {
if (!qualifier.useDefaultStartPrecision()) {
final SqlWriter.Frame frame = writer.startFunCall(start);
writer.print(startPrecision);
writer.endList(frame);
} else {
writer.keyword(start);
}
if (null != qualifier.timeUnitRange.endUnit) {
writer.keyword("TO");
final String end = qualifier.timeUnitRange.endUnit.name();
if ((TimeUnit.SECOND == qualifier.timeUnitRange.endUnit)
&& !qualifier.useDefaultFractionalSecondPrecision()) {
final SqlWriter.Frame frame = writer.startFunCall(end);
writer.print(fractionalSecondPrecision);
writer.endList(frame);
} else {
writer.keyword(end);
}
}
}
}
/** Converts an interval literal to a SQL string. The default implementation
* returns strings such as
* <code>INTERVAL '1 2:3:4' DAY(4) TO SECOND(4)</code>. */
public void unparseSqlIntervalLiteral(SqlWriter writer,
SqlIntervalLiteral literal, int leftPrec, int rightPrec) {
SqlIntervalLiteral.IntervalValue interval =
literal.getValueAs(SqlIntervalLiteral.IntervalValue.class);
writer.keyword("INTERVAL");
if (interval.getSign() == -1) {
writer.print("-");
}
writer.literal("'" + interval.getIntervalLiteral() + "'");
unparseSqlIntervalQualifier(writer, interval.getIntervalQualifier(),
RelDataTypeSystem.DEFAULT);
}
/**
* Returns whether the string contains any characters outside the
* comfortable 7-bit ASCII range (32 through 127, plus linefeed (10) and
* carriage return (13)).
*
* <p>Such characters can be used unquoted in SQL character literals.
*
* @param s String
* @return Whether string contains any non-7-bit-ASCII characters
*/
protected static boolean containsNonAscii(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < 32 && c != 10 && c != 13 || c >= 128) {
return true;
}
}
return false;
}
/**
* Converts a string into a unicode string literal. For example,
* <code>can't{tab}run\</code> becomes <code>u'can''t\0009run\\'</code>.
*/
public void quoteStringLiteralUnicode(StringBuilder buf, String val) {
buf.append("u&'");
for (int i = 0; i < val.length(); i++) {
char c = val.charAt(i);
if (c < 32 || c >= 128) {
buf.append('\\');
buf.append(HEXITS[(c >> 12) & 0xf]);
buf.append(HEXITS[(c >> 8) & 0xf]);
buf.append(HEXITS[(c >> 4) & 0xf]);
buf.append(HEXITS[c & 0xf]);
} else if (c == '\'' || c == '\\') {
buf.append(c);
buf.append(c);
} else {
buf.append(c);
}
}
buf.append("'");
}
private static final char[] HEXITS = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
};
/**
* Converts a string literal back into a string. For example, <code>'can''t
* run'</code> becomes <code>can't run</code>.
*/
public @Nullable String unquoteStringLiteral(@Nullable String val) {
if (val != null
&& val.startsWith(literalQuoteString)
&& val.endsWith(literalEndQuoteString)) {
final String stripped =
val.substring(literalQuoteString.length(),
val.length() - literalEndQuoteString.length());
return stripped.replace(literalEscapedQuote, literalEndQuoteString);
}
return val;
}
protected boolean allowsAs() {
return true;
}
// -- behaviors --
/** Whether a sub-query in the FROM clause must have an alias.
*
* <p>For example, in PostgreSQL, this query is legal:
*
* <blockquote>{@code SELECT * FROM (SELECT * FROM Emp) As e}</blockquote>
*
* <p>but remove the alias {@code e} and it is not:
*
* <blockquote>{@code SELECT * FROM (SELECT * FROM Emp)}</blockquote>
*
* <p>In Oracle, both queries are legal.
*/
public boolean requiresAliasForFromItems() {
return false;
}
/** Returns whether a qualified table in the FROM clause has an implicit alias
* which consists of just the table name.
*
* <p>For example, in {@link DatabaseProduct#ORACLE}
*
* <blockquote>SELECT * FROM sales.emp</blockquote>
*
* <p>is equivalent to
*
* <blockquote>SELECT * FROM sales.emp AS emp</blockquote>
*
* <p>and therefore
*
* <blockquote>SELECT emp.empno FROM sales.emp</blockquote>
*
* <p>is valid. But {@link DatabaseProduct#DB2} does not have an implicit
* alias, so the previous query it not valid; you need to write
*
* <blockquote>SELECT sales.emp.empno FROM sales.emp</blockquote>
*
* <p>Returns true for all databases except DB2.
*/
public boolean hasImplicitTableAlias() {
return true;
}
/**
* Converts a timestamp to a SQL timestamp literal, e.g.
* {@code TIMESTAMP '2009-12-17 12:34:56'}.
*
* <p>Timestamp values do not have a time zone. We therefore interpret them
* as the number of milliseconds after the UTC epoch, and the formatted
* value is that time in UTC.
*
* <p>In particular,
*
* <blockquote><code>quoteTimestampLiteral(new Timestamp(0));</code>
* </blockquote>
*
* <p>returns {@code TIMESTAMP '1970-01-01 00:00:00'}, regardless of the JVM's
* time zone.
*
* @param timestamp Timestamp
* @return SQL timestamp literal
*/
public String quoteTimestampLiteral(Timestamp timestamp) {
final SimpleDateFormat format = getDateFormatter("'TIMESTAMP' ''yyyy-MM-DD HH:mm:SS''");
return format.format(timestamp);
}
/**
* Returns the database this dialect belongs to,
* {@link SqlDialect.DatabaseProduct#UNKNOWN} if not known, never null.
*
* <p>Please be judicious in how you use this method. If you wish to determine
* whether a dialect has a particular capability or behavior, it is usually
* better to add a method to SqlDialect and override that method in particular
* sub-classes of SqlDialect.
*
* @return Database product
* @deprecated To be removed without replacement
*/
@Deprecated // to be removed before 2.0
public DatabaseProduct getDatabaseProduct() {
return databaseProduct;
}
/**
* Returns whether the dialect supports character set names as part of a
* data type, for instance {@code VARCHAR(30) CHARACTER SET `ISO-8859-1`}.
*/
@Pure
public boolean supportsCharSet() {
return true;
}
public boolean supportsAggregateFunction(SqlKind kind) {
switch (kind) {
case COUNT:
case SUM:
case SUM0:
case MIN:
case MAX:
return true;
default:
break;
}
return false;
}
/** Returns whether this dialect supports the use of FILTER clauses for
* aggregate functions. e.g. {@code COUNT(*) FILTER (WHERE a = 2)}. */
public boolean supportsAggregateFunctionFilter() {
return true;
}
/** Returns whether this dialect supports window functions (OVER clause). */
public boolean supportsWindowFunctions() {
return true;
}
/** Returns whether this dialect supports a given function or operator.
* It only applies to built-in scalar functions and operators, since
* user-defined functions and procedures should be read by JdbcSchema. */
public boolean supportsFunction(SqlOperator operator, RelDataType type,
List<RelDataType> paramTypes) {
switch (operator.kind) {
case AND:
case BETWEEN:
case CASE:
case CAST:
case CEIL:
case COALESCE:
case DIVIDE:
case EQUALS:
case FLOOR:
case GREATER_THAN:
case GREATER_THAN_OR_EQUAL:
case IN:
case IS_NULL:
case IS_NOT_NULL:
case LESS_THAN:
case LESS_THAN_OR_EQUAL:
case MINUS:
case MOD:
case NOT:
case NOT_IN:
case NOT_EQUALS:
case NVL:
case OR:
case PLUS:
case ROW:
case TIMES:
return true;
default:
return BUILT_IN_OPERATORS_LIST.contains(operator);
}
}
public CalendarPolicy getCalendarPolicy() {
return CalendarPolicy.NULL;
}
/** Returns whether this dialect supports a given type. */
public boolean supportsDataType(RelDataType type) {
return true;
}
/** Returns SqlNode for type in "cast(column as type)", which might be
* different between databases by type name, precision etc.
*
* <p>If this method returns null, the cast will be omitted. In the default
* implementation, this is the case for the NULL type, and therefore
* {@code CAST(NULL AS <nulltype>)} is rendered as {@code NULL}. */
public @Nullable SqlNode getCastSpec(RelDataType type) {
int maxPrecision = -1;
if (type instanceof AbstractSqlType) {
switch (type.getSqlTypeName()) {
case NULL:
return null;
case VARCHAR:
// if needed, adjust varchar length to max length supported by the system
maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName());
break;
default:
break;
}
String charSet = type.getCharset() != null && supportsCharSet()
? type.getCharset().name()
: null;
return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision);
}
return SqlTypeUtil.convertTypeToSpec(type);
}
/** Rewrite SINGLE_VALUE into expression based on database variants
* E.g. HSQLDB, MYSQL, ORACLE, etc
*/
public SqlNode rewriteSingleValueExpr(SqlNode aggCall) {
LOGGER.debug("SINGLE_VALUE rewrite not supported for {}", databaseProduct);
return aggCall;
}
/**
* Returns the SqlNode for emulating the null direction for the given field
* or <code>null</code> if no emulation needs to be done.
*
* @param node The SqlNode representing the expression
* @param nullsFirst Whether nulls should come first
* @param desc Whether the sort direction is
* {@link RelFieldCollation.Direction#DESCENDING} or
* {@link RelFieldCollation.Direction#STRICTLY_DESCENDING}
* @return A SqlNode for null direction emulation or <code>null</code> if not required
*/
public @Nullable SqlNode emulateNullDirection(SqlNode node, boolean nullsFirst,
boolean desc) {
return null;
}
public JoinType emulateJoinTypeForCrossJoin() {
return JoinType.COMMA;
}
protected @Nullable SqlNode emulateNullDirectionWithIsNull(SqlNode node,
boolean nullsFirst, boolean desc) {
// No need for emulation if the nulls will anyways come out the way we want
// them based on "nullsFirst" and "desc".
if (nullCollation.isDefaultOrder(nullsFirst, desc)) {
return null;
}
node = SqlStdOperatorTable.IS_NULL.createCall(SqlParserPos.ZERO, node);
if (nullsFirst) {
node = SqlStdOperatorTable.DESC.createCall(SqlParserPos.ZERO, node);
}
return node;
}
/**
* Returns whether the dialect supports OFFSET/FETCH clauses
* introduced by SQL:2008, for instance
* {@code OFFSET 10 ROWS FETCH NEXT 20 ROWS ONLY}.
* If false, we assume that the dialect supports the alternative syntax
* {@code LIMIT 20 OFFSET 10}.
*
* @deprecated This method is no longer used. To change how the dialect
* unparses offset/fetch, override the {@link #unparseOffsetFetch} method.
*/
@Deprecated
public boolean supportsOffsetFetch() {
return true;
}
/**
* Converts an offset and fetch into SQL.
*
* <p>At least one of {@code offset} and {@code fetch} must be provided.
*
* <p>Common options:
* <ul>
* <li>{@code OFFSET offset ROWS FETCH NEXT fetch ROWS ONLY}
* (ANSI standard SQL, Oracle, PostgreSQL, and the default)
* <li>{@code LIMIT fetch OFFSET offset} (Apache Hive, MySQL, Redshift)
* </ul>
*
* @param writer Writer
* @param offset Number of rows to skip before emitting, or null
* @param fetch Number of rows to fetch, or null
*
* @see #unparseFetchUsingAnsi(SqlWriter, SqlNode, SqlNode)
* @see #unparseFetchUsingLimit(SqlWriter, SqlNode, SqlNode)
*/
public void unparseOffsetFetch(SqlWriter writer, @Nullable SqlNode offset,
@Nullable SqlNode fetch) {
unparseFetchUsingAnsi(writer, offset, fetch);
}
/**
* Converts a fetch into a "SELECT TOP(fetch)".
*
* <p>A dialect that uses "TOP" syntax should override this method to print
* "TOP(fetch)", and override {@link #unparseOffsetFetch} to no-op.
*
* <p>The default implementation of this method is no-op.
*
* @param writer Writer
* @param offset Number of rows to skip before emitting, or null
* @param fetch Number of rows to fetch, or null
*/
public void unparseTopN(SqlWriter writer, @Nullable SqlNode offset, @Nullable SqlNode fetch) {
}
/** Unparses offset/fetch using ANSI standard "OFFSET offset ROWS FETCH NEXT
* fetch ROWS ONLY" syntax. */
protected static void unparseFetchUsingAnsi(SqlWriter writer, @Nullable SqlNode offset,
@Nullable SqlNode fetch) {
Preconditions.checkArgument(fetch != null || offset != null);
if (offset != null) {
writer.newlineAndIndent();
final SqlWriter.Frame offsetFrame =
writer.startList(SqlWriter.FrameTypeEnum.OFFSET);
writer.keyword("OFFSET");
offset.unparse(writer, -1, -1);
writer.keyword("ROWS");
writer.endList(offsetFrame);
}
if (fetch != null) {
writer.newlineAndIndent();
final SqlWriter.Frame fetchFrame =
writer.startList(SqlWriter.FrameTypeEnum.FETCH);
writer.keyword("FETCH");
writer.keyword("NEXT");
fetch.unparse(writer, -1, -1);
writer.keyword("ROWS");
writer.keyword("ONLY");
writer.endList(fetchFrame);
}
}
/** Unparses offset/fetch using "LIMIT fetch OFFSET offset" syntax. */
protected static void unparseFetchUsingLimit(SqlWriter writer, @Nullable SqlNode offset,
@Nullable SqlNode fetch) {
Preconditions.checkArgument(fetch != null || offset != null);
unparseLimit(writer, fetch);
unparseOffset(writer, offset);
}
protected static void unparseLimit(SqlWriter writer, @Nullable SqlNode fetch) {
if (fetch != null) {
writer.newlineAndIndent();
final SqlWriter.Frame fetchFrame =
writer.startList(SqlWriter.FrameTypeEnum.FETCH);
writer.keyword("LIMIT");
fetch.unparse(writer, -1, -1);
writer.endList(fetchFrame);
}
}
protected static void unparseOffset(SqlWriter writer, @Nullable SqlNode offset) {
if (offset != null) {
writer.newlineAndIndent();
final SqlWriter.Frame offsetFrame =
writer.startList(SqlWriter.FrameTypeEnum.OFFSET);
writer.keyword("OFFSET");
offset.unparse(writer, -1, -1);
writer.endList(offsetFrame);
}
}
/**
* Returns whether the dialect supports nested aggregations, for instance
* {@code SELECT SUM(SUM(1)) }.
*/
public boolean supportsNestedAggregations() {
return true;
}
/**
* Returns whether this dialect supports "WITH ROLLUP" in the "GROUP BY"
* clause.
*
* <p>For instance, in MySQL version 5,
*
* <blockquote>
* <code>
* SELECT deptno, job, COUNT(*) AS c
* FROM emp
* GROUP BY deptno, job WITH ROLLUP
* </code>
* </blockquote>
*
* <p>is equivalent to standard SQL
*
* <blockquote>
* <code>
* SELECT deptno, job, COUNT(*) AS c
* FROM emp
* GROUP BY ROLLUP(deptno, job)
* ORDER BY deptno, job
* </code>
* </blockquote>
*
* <p>The "WITH ROLLUP" clause was introduced in MySQL and is not standard
* SQL.
*
* <p>See also {@link #supportsAggregateFunction(SqlKind)} applied to
* {@link SqlKind#ROLLUP}, which returns true in MySQL 8 and higher.
*/
public boolean supportsGroupByWithRollup() {
return false;
}
/**