/
IgniteH2Indexing.java
3227 lines (2581 loc) · 103 KB
/
IgniteH2Indexing.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.ignite.internal.processors.query.h2;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.cache.Cache;
import javax.cache.CacheException;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cache.CacheMemoryMode;
import org.apache.ignite.cache.QueryIndexType;
import org.apache.ignite.cache.query.QueryCancelledException;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.SqlQuery;
import org.apache.ignite.cache.query.annotations.QuerySqlFunction;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.GridTopic;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.jdbc2.JdbcSqlFieldsQuery;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.CacheEntryImpl;
import org.apache.ignite.internal.processors.cache.CacheObject;
import org.apache.ignite.internal.processors.cache.CacheObjectContext;
import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
import org.apache.ignite.internal.processors.cache.GridCacheAffinityManager;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.IgniteInternalCache;
import org.apache.ignite.internal.processors.cache.QueryCursorImpl;
import org.apache.ignite.internal.processors.cache.query.GridCacheQueryMarshallable;
import org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery;
import org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode;
import org.apache.ignite.internal.processors.query.GridRunningQueryInfo;
import org.apache.ignite.internal.processors.query.GridQueryCancel;
import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
import org.apache.ignite.internal.processors.query.GridQueryFieldsResult;
import org.apache.ignite.internal.processors.query.GridQueryFieldsResultAdapter;
import org.apache.ignite.internal.processors.query.GridQueryIndexDescriptor;
import org.apache.ignite.internal.processors.query.GridQueryIndexing;
import org.apache.ignite.internal.processors.query.GridQueryProperty;
import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
import org.apache.ignite.internal.processors.query.IgniteSQLException;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2DefaultTableEngine;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2KeyValueRowOffheap;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2KeyValueRowOnheap;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2Row;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2RowFactory;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2TreeIndex;
import org.apache.ignite.internal.processors.query.h2.opt.GridH2ValueCacheObject;
import org.apache.ignite.internal.processors.query.h2.opt.GridLuceneIndex;
import org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser;
import org.apache.ignite.internal.processors.query.h2.sql.GridSqlQuerySplitter;
import org.apache.ignite.internal.processors.query.h2.twostep.GridMapQueryExecutor;
import org.apache.ignite.internal.processors.query.h2.twostep.GridReduceQueryExecutor;
import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor;
import org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashMap;
import org.apache.ignite.internal.util.GridEmptyCloseableIterator;
import org.apache.ignite.internal.util.GridSpinBusyLock;
import org.apache.ignite.internal.util.lang.GridCloseableIterator;
import org.apache.ignite.internal.util.lang.GridPlainRunnable;
import org.apache.ignite.internal.util.lang.IgniteInClosure2X;
import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeGuard;
import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMemory;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.LT;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiClosure;
import org.apache.ignite.lang.IgniteBiPredicate;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.lang.IgniteInClosure;
import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.marshaller.jdk.JdkMarshaller;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.spi.indexing.IndexingQueryFilter;
import org.h2.api.ErrorCode;
import org.h2.api.JavaObjectSerializer;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.index.Index;
import org.h2.index.SpatialIndex;
import org.h2.jdbc.JdbcConnection;
import org.h2.jdbc.JdbcPreparedStatement;
import org.h2.jdbc.JdbcStatement;
import org.h2.message.DbException;
import org.h2.mvstore.cache.CacheLongKeyLIRS;
import org.h2.result.SortOrder;
import org.h2.server.web.WebServer;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
import org.h2.tools.Server;
import org.h2.util.JdbcUtils;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueByte;
import org.h2.value.ValueBytes;
import org.h2.value.ValueDate;
import org.h2.value.ValueDecimal;
import org.h2.value.ValueDouble;
import org.h2.value.ValueFloat;
import org.h2.value.ValueGeometry;
import org.h2.value.ValueInt;
import org.h2.value.ValueJavaObject;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
import org.h2.value.ValueShort;
import org.h2.value.ValueString;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueUuid;
import org.jetbrains.annotations.Nullable;
import org.jsr166.ConcurrentHashMap8;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_H2_DEBUG_CONSOLE;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_H2_DEBUG_CONSOLE_PORT;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_H2_INDEXING_CACHE_CLEANUP_PERIOD;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_H2_INDEXING_CACHE_THREAD_USAGE_TIMEOUT;
import static org.apache.ignite.IgniteSystemProperties.getInteger;
import static org.apache.ignite.IgniteSystemProperties.getString;
import static org.apache.ignite.internal.processors.cache.query.GridCacheQueryType.SQL;
import static org.apache.ignite.internal.processors.cache.query.GridCacheQueryType.SQL_FIELDS;
import static org.apache.ignite.internal.processors.cache.query.GridCacheQueryType.TEXT;
import static org.apache.ignite.internal.processors.query.h2.opt.GridH2AbstractKeyValueRow.KEY_COL;
import static org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryType.LOCAL;
import static org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryType.PREPARE;
/**
* Indexing implementation based on H2 database engine. In this implementation main query language is SQL,
* fulltext indexing can be performed using Lucene. For each registered space
* the SPI will create respective schema, for default space (where space name is null) schema
* with name {@code ""} will be used. To avoid name conflicts user should not explicitly name
* a schema {@code ""}.
* <p>
* For each registered {@link GridQueryTypeDescriptor} this SPI will create respective SQL table with
* {@code '_key'} and {@code '_val'} fields for key and value, and fields from
* {@link GridQueryTypeDescriptor#fields()}.
* For each table it will create indexes declared in {@link GridQueryTypeDescriptor#indexes()}.
*/
@SuppressWarnings({"UnnecessaryFullyQualifiedName", "NonFinalStaticVariableUsedInClassInitialization"})
public class IgniteH2Indexing implements GridQueryIndexing {
/** Default DB options. */
private static final String DB_OPTIONS = ";LOCK_MODE=3;MULTI_THREADED=1;DB_CLOSE_ON_EXIT=FALSE" +
";DEFAULT_LOCK_TIMEOUT=10000;FUNCTIONS_IN_SCHEMA=true;OPTIMIZE_REUSE_RESULTS=0;QUERY_CACHE_SIZE=0" +
";RECOMPILE_ALWAYS=1;MAX_OPERATION_MEMORY=0;NESTED_JOINS=0;BATCH_JOINS=1" +
";ROW_FACTORY=\"" + GridH2RowFactory.class.getName() + "\"" +
";DEFAULT_TABLE_ENGINE=" + GridH2DefaultTableEngine.class.getName();
/** */
private static final int PREPARED_STMT_CACHE_SIZE = 256;
/** */
private static final int TWO_STEP_QRY_CACHE_SIZE = 1024;
/** Field name for key. */
public static final String KEY_FIELD_NAME = "_KEY";
/** Field name for value. */
public static final String VAL_FIELD_NAME = "_VAL";
/** */
private static final Field COMMAND_FIELD;
/** */
private static final char ESC_CH = '\"';
/** */
private static final String ESC_STR = ESC_CH + "" + ESC_CH;
/** The period of clean up the {@link #stmtCache}. */
private final Long CLEANUP_STMT_CACHE_PERIOD = Long.getLong(IGNITE_H2_INDEXING_CACHE_CLEANUP_PERIOD, 10_000);
/** The timeout to remove entry from the {@link #stmtCache} if the thread doesn't perform any queries. */
private final Long STATEMENT_CACHE_THREAD_USAGE_TIMEOUT =
Long.getLong(IGNITE_H2_INDEXING_CACHE_THREAD_USAGE_TIMEOUT, 600 * 1000);
/** */
private GridTimeoutProcessor.CancelableTask stmtCacheCleanupTask;
/**
* Command in H2 prepared statement.
*/
static {
// Initialize system properties for H2.
System.setProperty("h2.objectCache", "false");
System.setProperty("h2.serializeJavaObject", "false");
System.setProperty("h2.objectCacheMaxPerElementSize", "0"); // Avoid ValueJavaObject caching.
try {
COMMAND_FIELD = JdbcPreparedStatement.class.getDeclaredField("command");
COMMAND_FIELD.setAccessible(true);
}
catch (NoSuchFieldException e) {
throw new IllegalStateException("Check H2 version in classpath.", e);
}
}
/** Logger. */
@LoggerResource
private IgniteLogger log;
/** Node ID. */
private UUID nodeId;
/** */
private Marshaller marshaller;
/** Collection of schemaNames and registered tables. */
private final ConcurrentMap<String, Schema> schemas = new ConcurrentHashMap8<>();
/** */
private String dbUrl = "jdbc:h2:mem:";
/** */
private final Collection<Connection> conns = Collections.synchronizedCollection(new ArrayList<Connection>());
/** */
private GridMapQueryExecutor mapQryExec;
/** */
private GridReduceQueryExecutor rdcQryExec;
/** space name -> schema name */
private final Map<String, String> space2schema = new ConcurrentHashMap8<>();
/** */
private AtomicLong qryIdGen;
/** */
private GridSpinBusyLock busyLock;
/** */
private final ConcurrentMap<Long, GridRunningQueryInfo> runs = new ConcurrentHashMap8<>();
/** */
private final ThreadLocal<ConnectionWrapper> connCache = new ThreadLocal<ConnectionWrapper>() {
@Nullable @Override public ConnectionWrapper get() {
ConnectionWrapper c = super.get();
boolean reconnect = true;
try {
reconnect = c == null || c.connection().isClosed();
}
catch (SQLException e) {
U.warn(log, "Failed to check connection status.", e);
}
if (reconnect) {
c = initialValue();
set(c);
// Reset statement cache when new connection is created.
stmtCache.remove(Thread.currentThread());
}
return c;
}
@Nullable @Override protected ConnectionWrapper initialValue() {
Connection c;
try {
c = DriverManager.getConnection(dbUrl);
}
catch (SQLException e) {
throw new IgniteSQLException("Failed to initialize DB connection: " + dbUrl, e);
}
conns.add(c);
return new ConnectionWrapper(c);
}
};
/** */
private volatile GridKernalContext ctx;
/** */
private final DmlStatementsProcessor dmlProc = new DmlStatementsProcessor(this);
/** */
private final ConcurrentMap<String, GridH2Table> dataTables = new ConcurrentHashMap8<>();
/** Statement cache. */
private final ConcurrentHashMap<Thread, StatementCache> stmtCache = new ConcurrentHashMap<>();
/** */
private final GridBoundedConcurrentLinkedHashMap<TwoStepCachedQueryKey, TwoStepCachedQuery> twoStepCache =
new GridBoundedConcurrentLinkedHashMap<>(TWO_STEP_QRY_CACHE_SIZE);
/** */
private final IgniteInClosure<? super IgniteInternalFuture<?>> logger = new IgniteInClosure<IgniteInternalFuture<?>>() {
@Override public void apply(IgniteInternalFuture<?> fut) {
try {
fut.get();
}
catch (IgniteCheckedException e) {
U.error(log, e.getMessage(), e);
}
}
};
/**
* @return Kernal context.
*/
public GridKernalContext kernalContext() {
return ctx;
}
/**
* @param space Space.
* @return Connection.
*/
public Connection connectionForSpace(@Nullable String space) {
try {
return connectionForThread(schema(space));
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
/**
* @return Logger.
*/
IgniteLogger getLogger() {
return log;
}
/**
* @param c Connection.
* @param sql SQL.
* @param useStmtCache If {@code true} uses statement cache.
* @return Prepared statement.
* @throws SQLException If failed.
*/
private PreparedStatement prepareStatement(Connection c, String sql, boolean useStmtCache) throws SQLException {
if (useStmtCache) {
Thread curThread = Thread.currentThread();
StatementCache cache = stmtCache.get(curThread);
if (cache == null) {
StatementCache cache0 = new StatementCache(PREPARED_STMT_CACHE_SIZE);
cache = stmtCache.putIfAbsent(curThread, cache0);
if (cache == null)
cache = cache0;
}
cache.updateLastUsage();
PreparedStatement stmt = cache.get(sql);
if (stmt != null && !stmt.isClosed() && !((JdbcStatement)stmt).wasCancelled()) {
assert stmt.getConnection() == c;
return stmt;
}
stmt = c.prepareStatement(sql);
cache.put(sql, stmt);
return stmt;
}
else
return c.prepareStatement(sql);
}
/** {@inheritDoc} */
@Override public PreparedStatement prepareNativeStatement(String schema, String sql) throws SQLException {
return prepareStatement(connectionForSpace(schema), sql, false);
}
/**
* Gets DB connection.
*
* @param schema Whether to set schema for connection or not.
* @return DB connection.
* @throws IgniteCheckedException In case of error.
*/
private Connection connectionForThread(@Nullable String schema) throws IgniteCheckedException {
ConnectionWrapper c = connCache.get();
if (c == null)
throw new IgniteCheckedException("Failed to get DB connection for thread (check log for details).");
if (schema != null && !F.eq(c.schema(), schema)) {
Statement stmt = null;
try {
stmt = c.connection().createStatement();
stmt.executeUpdate("SET SCHEMA " + schema);
if (log.isDebugEnabled())
log.debug("Set schema: " + schema);
c.schema(schema);
}
catch (SQLException e) {
throw new IgniteSQLException("Failed to set schema for DB connection for thread [schema=" +
schema + "]", e);
}
finally {
U.close(stmt, log);
}
}
return c.connection();
}
/**
* Creates DB schema if it has not been created yet.
*
* @param schema Schema name.
* @throws IgniteCheckedException If failed to create db schema.
*/
private void createSchema(String schema) throws IgniteCheckedException {
executeStatement("INFORMATION_SCHEMA", "CREATE SCHEMA IF NOT EXISTS " + schema);
if (log.isDebugEnabled())
log.debug("Created H2 schema for index database: " + schema);
}
/**
* Creates DB schema if it has not been created yet.
*
* @param schema Schema name.
* @throws IgniteCheckedException If failed to create db schema.
*/
private void dropSchema(String schema) throws IgniteCheckedException {
executeStatement("INFORMATION_SCHEMA", "DROP SCHEMA IF EXISTS " + schema);
if (log.isDebugEnabled())
log.debug("Dropped H2 schema for index database: " + schema);
}
/**
* @param schema Schema
* @param sql SQL statement.
* @throws IgniteCheckedException If failed.
*/
public void executeStatement(String schema, String sql) throws IgniteCheckedException {
Statement stmt = null;
try {
Connection c = connectionForThread(schema);
stmt = c.createStatement();
stmt.executeUpdate(sql);
}
catch (SQLException e) {
onSqlException();
throw new IgniteSQLException("Failed to execute statement: " + sql, e);
}
finally {
U.close(stmt, log);
}
}
/**
* Removes entry with specified key from any tables (if exist).
*
* @param spaceName Space name.
* @param key Key.
* @param tblToUpdate Table to update.
* @throws IgniteCheckedException In case of error.
*/
private void removeKey(@Nullable String spaceName, CacheObject key, TableDescriptor tblToUpdate)
throws IgniteCheckedException {
try {
Collection<TableDescriptor> tbls = tables(schema(spaceName));
Class<?> keyCls = getClass(objectContext(spaceName), key);
for (TableDescriptor tbl : tbls) {
if (tbl != tblToUpdate && tbl.type().keyClass().isAssignableFrom(keyCls)) {
if (tbl.tbl.update(key, null, 0, true)) {
if (tbl.luceneIdx != null)
tbl.luceneIdx.remove(key);
return;
}
}
}
}
catch (Exception e) {
throw new IgniteCheckedException("Failed to remove key: " + key, e);
}
}
/**
* Binds object to prepared statement.
*
* @param stmt SQL statement.
* @param idx Index.
* @param obj Value to store.
* @throws IgniteCheckedException If failed.
*/
private void bindObject(PreparedStatement stmt, int idx, @Nullable Object obj) throws IgniteCheckedException {
try {
if (obj == null)
stmt.setNull(idx, Types.VARCHAR);
else
stmt.setObject(idx, obj);
}
catch (SQLException e) {
throw new IgniteCheckedException("Failed to bind parameter [idx=" + idx + ", obj=" + obj + ", stmt=" +
stmt + ']', e);
}
}
/**
* Handles SQL exception.
*/
private void onSqlException() {
Connection conn = connCache.get().connection();
connCache.set(null);
if (conn != null) {
conns.remove(conn);
// Reset connection to receive new one at next call.
U.close(conn, log);
}
}
/** {@inheritDoc} */
@Override public void store(@Nullable String spaceName, GridQueryTypeDescriptor type, CacheObject k, CacheObject v,
byte[] ver, long expirationTime) throws IgniteCheckedException {
TableDescriptor tbl = tableDescriptor(spaceName, type);
removeKey(spaceName, k, tbl);
if (tbl == null)
return; // Type was rejected.
if (expirationTime == 0)
expirationTime = Long.MAX_VALUE;
tbl.tbl.update(k, v, expirationTime, false);
if (tbl.luceneIdx != null)
tbl.luceneIdx.store(k, v, ver, expirationTime);
}
/**
* @param o Object.
* @return {@code true} If it is a binary object.
*/
private boolean isBinary(CacheObject o) {
if (ctx == null)
return false;
return ctx.cacheObjects().isBinaryObject(o);
}
/**
* @param coctx Cache object context.
* @param o Object.
* @return Object class.
*/
private Class<?> getClass(CacheObjectContext coctx, CacheObject o) {
return isBinary(o) ?
Object.class :
o.value(coctx, false).getClass();
}
/**
* @param space Space.
* @return Cache object context.
*/
private CacheObjectContext objectContext(String space) {
if (ctx == null)
return null;
return ctx.cache().internalCache(space).context().cacheObjectContext();
}
/**
* @param space Space.
* @return Cache object context.
*/
private GridCacheContext cacheContext(String space) {
if (ctx == null)
return null;
return ctx.cache().internalCache(space).context();
}
/** {@inheritDoc} */
@Override public void remove(@Nullable String spaceName, CacheObject key, CacheObject val) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Removing key from cache query index [locId=" + nodeId + ", key=" + key + ", val=" + val + ']');
CacheObjectContext coctx = objectContext(spaceName);
Class<?> keyCls = getClass(coctx, key);
Class<?> valCls = val == null ? null : getClass(coctx, val);
for (TableDescriptor tbl : tables(schema(spaceName))) {
if (tbl.type().keyClass().isAssignableFrom(keyCls)
&& (val == null || tbl.type().valueClass().isAssignableFrom(valCls))) {
if (tbl.tbl.update(key, val, 0, true)) {
if (tbl.luceneIdx != null)
tbl.luceneIdx.remove(key);
return;
}
}
}
}
/** {@inheritDoc} */
@Override public void onSwap(@Nullable String spaceName, CacheObject key) throws IgniteCheckedException {
Schema schema = schemas.get(schema(spaceName));
if (schema == null)
return;
Class<?> keyCls = getClass(objectContext(spaceName), key);
for (TableDescriptor tbl : schema.tbls.values()) {
if (tbl.type().keyClass().isAssignableFrom(keyCls)) {
try {
if (tbl.tbl.onSwap(key))
return;
}
catch (IgniteCheckedException e) {
throw new IgniteCheckedException(e);
}
}
}
}
/** {@inheritDoc} */
@Override public void onUnswap(@Nullable String spaceName, CacheObject key, CacheObject val)
throws IgniteCheckedException {
assert val != null;
CacheObjectContext coctx = objectContext(spaceName);
Class<?> keyCls = getClass(coctx, key);
Class<?> valCls = getClass(coctx, val);
for (TableDescriptor tbl : tables(schema(spaceName))) {
if (tbl.type().keyClass().isAssignableFrom(keyCls)
&& tbl.type().valueClass().isAssignableFrom(valCls)) {
try {
if (tbl.tbl.onUnswap(key, val))
return;
}
catch (IgniteCheckedException e) {
throw new IgniteCheckedException(e);
}
}
}
}
/**
* Drops table form h2 database and clear all related indexes (h2 text, lucene).
*
* @param tbl Table to unregister.
* @throws IgniteCheckedException If failed to unregister.
*/
private void removeTable(TableDescriptor tbl) throws IgniteCheckedException {
assert tbl != null;
if (log.isDebugEnabled())
log.debug("Removing query index table: " + tbl.fullTableName());
Connection c = connectionForThread(tbl.schemaName());
Statement stmt = null;
try {
// NOTE: there is no method dropIndex() for lucene engine correctly working.
// So we have to drop all lucene index.
// FullTextLucene.dropAll(c); TODO: GG-4015: fix this
stmt = c.createStatement();
String sql = "DROP TABLE IF EXISTS " + tbl.fullTableName();
if (log.isDebugEnabled())
log.debug("Dropping database index table with SQL: " + sql);
stmt.executeUpdate(sql);
}
catch (SQLException e) {
onSqlException();
throw new IgniteSQLException("Failed to drop database index table [type=" + tbl.type().name() +
", table=" + tbl.fullTableName() + "]", IgniteQueryErrorCode.TABLE_DROP_FAILED, e);
}
finally {
U.close(stmt, log);
}
tbl.onDrop();
tbl.schema.tbls.remove(tbl.typeName());
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public <K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalText(
@Nullable String spaceName, String qry, GridQueryTypeDescriptor type,
IndexingQueryFilter filters) throws IgniteCheckedException {
TableDescriptor tbl = tableDescriptor(spaceName, type);
if (tbl != null && tbl.luceneIdx != null) {
GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, TEXT, spaceName,
U.currentTimeMillis(), null, true);
try {
runs.put(run.id(), run);
return tbl.luceneIdx.query(qry, filters);
}
finally {
runs.remove(run.id());
}
}
return new GridEmptyCloseableIterator<>();
}
/** {@inheritDoc} */
@Override public void unregisterType(@Nullable String spaceName, GridQueryTypeDescriptor type)
throws IgniteCheckedException {
TableDescriptor tbl = tableDescriptor(spaceName, type);
if (tbl != null)
removeTable(tbl);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridQueryFieldsResult queryLocalSqlFields(@Nullable final String spaceName, final String qry,
@Nullable final Collection<Object> params, final IndexingQueryFilter filters, boolean enforceJoinOrder,
final int timeout, final GridQueryCancel cancel)
throws IgniteCheckedException {
final Connection conn = connectionForSpace(spaceName);
setupConnection(conn, false, enforceJoinOrder);
final PreparedStatement stmt = preparedStatementWithParams(conn, qry, params, true);
Prepared p = GridSqlQueryParser.prepared((JdbcPreparedStatement)stmt);
if (!p.isQuery()) {
SqlFieldsQuery fldsQry = new SqlFieldsQuery(qry);
if (params != null)
fldsQry.setArgs(params.toArray());
fldsQry.setEnforceJoinOrder(enforceJoinOrder);
fldsQry.setTimeout(timeout, TimeUnit.MILLISECONDS);
return dmlProc.updateLocalSqlFields(spaceName, stmt, fldsQry, filters, cancel);
}
List<GridQueryFieldMetadata> meta;
try {
meta = meta(stmt.getMetaData());
}
catch (SQLException e) {
throw new IgniteCheckedException("Cannot prepare query metadata", e);
}
final GridH2QueryContext ctx = new GridH2QueryContext(nodeId, nodeId, 0, LOCAL)
.filter(filters).distributedJoins(false);
return new GridQueryFieldsResultAdapter(meta, null) {
@Override public GridCloseableIterator<List<?>> iterator() throws IgniteCheckedException {
assert GridH2QueryContext.get() == null;
GridH2QueryContext.set(ctx);
GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, SQL_FIELDS,
spaceName, U.currentTimeMillis(), cancel, true);
runs.putIfAbsent(run.id(), run);
try {
ResultSet rs = executeSqlQueryWithTimer(spaceName, stmt, conn, qry, params, timeout, cancel);
return new FieldsIterator(rs);
}
finally {
GridH2QueryContext.clearThreadLocal();
runs.remove(run.id());
}
}
};
}
/**
* @param rsMeta Metadata.
* @return List of fields metadata.
* @throws SQLException If failed.
*/
private static List<GridQueryFieldMetadata> meta(ResultSetMetaData rsMeta) throws SQLException {
List<GridQueryFieldMetadata> meta = new ArrayList<>(rsMeta.getColumnCount());
for (int i = 1; i <= rsMeta.getColumnCount(); i++) {
String schemaName = rsMeta.getSchemaName(i);
String typeName = rsMeta.getTableName(i);
String name = rsMeta.getColumnLabel(i);
String type = rsMeta.getColumnClassName(i);
if (type == null) // Expression always returns NULL.
type = Void.class.getName();
meta.add(new SqlFieldMetadata(schemaName, typeName, name, type));
}
return meta;
}
/**
* @param stmt Prepared statement.
* @return Command type.
*/
private static int commandType(PreparedStatement stmt) {
try {
return ((CommandInterface)COMMAND_FIELD.get(stmt)).getCommandType();
}
catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
/**
* Stores rule for constructing schemaName according to cache configuration.
*
* @param ccfg Cache configuration.
* @return Proper schema name according to ANSI-99 standard.
*/
private static String schemaNameFromCacheConf(CacheConfiguration<?,?> ccfg) {
if (ccfg.getSqlSchema() == null)
return escapeName(ccfg.getName(), true);
if (ccfg.getSqlSchema().charAt(0) == ESC_CH)
return ccfg.getSqlSchema();
return ccfg.isSqlEscapeAll() ? escapeName(ccfg.getSqlSchema(), true) : ccfg.getSqlSchema().toUpperCase();
}
/**
* Prepares sql statement.
*
* @param conn Connection.
* @param sql Sql.
* @param params Params.
* @param useStmtCache If {@code true} use stmt cache.
* @return Prepared statement with set parameters.
* @throws IgniteCheckedException If failed.
*/
private PreparedStatement preparedStatementWithParams(Connection conn, String sql, Collection<Object> params,
boolean useStmtCache) throws IgniteCheckedException {
final PreparedStatement stmt;
try {
stmt = prepareStatement(conn, sql, useStmtCache);
}
catch (SQLException e) {
throw new IgniteCheckedException("Failed to parse SQL query: " + sql, e);
}
bindParameters(stmt, params);
return stmt;
}
/**
* Executes sql query statement.
*
* @param conn Connection,.
* @param stmt Statement.
* @param cancel Query cancel.
* @return Result.
* @throws IgniteCheckedException If failed.
*/
private ResultSet executeSqlQuery(final Connection conn, final PreparedStatement stmt,
int timeoutMillis, @Nullable GridQueryCancel cancel)
throws IgniteCheckedException {
if (timeoutMillis > 0)
((Session)((JdbcConnection)conn).getSession()).setQueryTimeout(timeoutMillis);
if (cancel != null) {
cancel.set(new Runnable() {
@Override public void run() {
try {
stmt.cancel();
}
catch (SQLException ignored) {
// No-op.
}
}
});
}
try {
return stmt.executeQuery();
}
catch (SQLException e) {
// Throw special exception.
if (e.getErrorCode() == ErrorCode.STATEMENT_WAS_CANCELED)
throw new QueryCancelledException();
throw new IgniteCheckedException("Failed to execute SQL query.", e);
}
finally {
if (timeoutMillis > 0)
((Session)((JdbcConnection)conn).getSession()).setQueryTimeout(0);
}
}
/**
* Executes sql query and prints warning if query is too slow..
*
* @param space Space name.