forked from StarRocks/starrocks
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Database.java
794 lines (704 loc) · 28.1 KB
/
Database.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
// This file is made available under Elastic License 2.0.
// This file is based on code available under the Apache license here:
// https://github.com/apache/incubator-doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/catalog/Database.java
// 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 com.starrocks.catalog;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.starrocks.catalog.Table.TableType;
import com.starrocks.cluster.ClusterNamespace;
import com.starrocks.common.Config;
import com.starrocks.common.DdlException;
import com.starrocks.common.ErrorCode;
import com.starrocks.common.ErrorReport;
import com.starrocks.common.FeConstants;
import com.starrocks.common.FeMetaVersion;
import com.starrocks.common.Pair;
import com.starrocks.common.UserException;
import com.starrocks.common.io.Text;
import com.starrocks.common.io.Writable;
import com.starrocks.common.util.DebugUtil;
import com.starrocks.common.util.QueryableReentrantReadWriteLock;
import com.starrocks.common.util.Util;
import com.starrocks.persist.CreateTableInfo;
import com.starrocks.persist.DropInfo;
import com.starrocks.server.GlobalStateMgr;
import com.starrocks.system.SystemInfoService;
import com.starrocks.task.AgentBatchTask;
import com.starrocks.task.AgentTask;
import com.starrocks.task.AgentTaskExecutor;
import org.apache.hadoop.util.ThreadUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.zip.Adler32;
/**
* Internal representation of db-related metadata. Owned by GlobalStateMgr instance.
* Not thread safe.
* <p/>
* The static initialization method loadDb is the only way to construct a Db
* object.
* <p/>
* Tables are stored in a map from the table name to the table object. They may
* be loaded 'eagerly' at construction or 'lazily' on first reference. Tables
* are accessed via getTable which may trigger a metadata read in two cases: *
* if the table has never been loaded * if the table loading failed on the
* previous attempt
*/
public class Database extends MetaObject implements Writable {
private static final Logger LOG = LogManager.getLogger(Database.class);
// empirical value.
// assume that the time a lock is held by thread is less than 100ms
public static final long TRY_LOCK_TIMEOUT_MS = 100L;
public static final long SLOW_LOCK_MS = 3000L;
public static final long SLOW_LOCK_LOG_EVERY_MS = 3000L;
private long id;
private String fullQualifiedName;
private QueryableReentrantReadWriteLock rwLock;
// table family group map
private Map<Long, Table> idToTable;
private Map<String, Table> nameToTable;
// user define function
private ConcurrentMap<String, ImmutableList<Function>> name2Function = Maps.newConcurrentMap();
private volatile long dataQuotaBytes;
private volatile long replicaQuotaSize;
private long lastSlowLockLogTime = 0;
public Database() {
this(0, null);
}
public Database(long id, String name) {
this.id = id;
this.fullQualifiedName = name;
if (this.fullQualifiedName == null) {
this.fullQualifiedName = "";
}
this.rwLock = new QueryableReentrantReadWriteLock(true);
this.idToTable = new ConcurrentHashMap<>();
this.nameToTable = new ConcurrentHashMap<>();
this.dataQuotaBytes = FeConstants.default_db_data_quota_bytes;
this.replicaQuotaSize = FeConstants.default_db_replica_quota_size;
}
public void readLock() {
long startMs = System.nanoTime() / 1000000;
this.rwLock.readLock().lock();
long endMs = System.nanoTime() / 1000000;
if (endMs - startMs > SLOW_LOCK_MS && endMs > lastSlowLockLogTime + SLOW_LOCK_LOG_EVERY_MS) {
lastSlowLockLogTime = endMs;
LOG.warn("slow read lock db:" + id + " " + fullQualifiedName + " " + (endMs - startMs) + "ms",
new Exception());
}
}
public boolean tryReadLock(long timeout, TimeUnit unit) {
try {
if (!this.rwLock.readLock().tryLock(timeout, unit)) {
Thread owner = rwLock.getOwner();
if (owner != null) {
LOG.warn("database lock is held by: {}", Util.dumpThread(owner, 50));
}
return false;
}
return true;
} catch (InterruptedException e) {
LOG.warn("failed to try read lock at db[" + id + "]", e);
return false;
}
}
public void readUnlock() {
this.rwLock.readLock().unlock();
}
public void writeLock() {
long startMs = System.nanoTime() / 1000000;
this.rwLock.writeLock().lock();
long endMs = System.nanoTime() / 1000000;
if (endMs - startMs > SLOW_LOCK_MS && endMs > lastSlowLockLogTime + SLOW_LOCK_LOG_EVERY_MS) {
lastSlowLockLogTime = endMs;
LOG.warn("slow write lock db:" + id + " " + fullQualifiedName + " " + (endMs - startMs) + "ms",
new Exception());
}
}
public boolean tryWriteLock(long timeout, TimeUnit unit) {
try {
if (!this.rwLock.writeLock().tryLock(timeout, unit)) {
Thread owner = rwLock.getOwner();
if (owner != null) {
LOG.warn("database lock is held by: {}", Util.dumpThread(owner, 50));
}
return false;
}
return true;
} catch (InterruptedException e) {
LOG.warn("failed to try write lock at db[" + id + "]", e);
return false;
}
}
public void writeUnlock() {
this.rwLock.writeLock().unlock();
}
public boolean isWriteLockHeldByCurrentThread() {
return this.rwLock.writeLock().isHeldByCurrentThread();
}
public long getId() {
return id;
}
public String getFullName() {
return fullQualifiedName;
}
public void setNameWithLock(String newName) {
writeLock();
try {
this.fullQualifiedName = newName;
} finally {
writeUnlock();
}
}
public void setDataQuotaWithLock(long newQuota) {
Preconditions.checkArgument(newQuota >= 0L);
LOG.info("database[{}] set quota from {} to {}", fullQualifiedName, dataQuotaBytes, newQuota);
writeLock();
try {
this.dataQuotaBytes = newQuota;
} finally {
writeUnlock();
}
}
public void setReplicaQuotaWithLock(long newQuota) {
Preconditions.checkArgument(newQuota >= 0L);
LOG.info("database[{}] set replica quota from {} to {}", fullQualifiedName, replicaQuotaSize, newQuota);
writeLock();
try {
this.replicaQuotaSize = newQuota;
} finally {
writeUnlock();
}
}
public long getDataQuota() {
return dataQuotaBytes;
}
public long getReplicaQuota() {
return replicaQuotaSize;
}
public long getUsedDataQuotaWithLock() {
long usedDataQuota = 0;
readLock();
try {
for (Table table : this.idToTable.values()) {
if (!table.isLocalTable()) {
continue;
}
OlapTable olapTable = (OlapTable) table;
usedDataQuota = usedDataQuota + olapTable.getDataSize();
}
return usedDataQuota;
} finally {
readUnlock();
}
}
public long getReplicaQuotaLeftWithLock() {
long usedReplicaQuota = 0;
readLock();
try {
for (Table table : this.idToTable.values()) {
if (!table.isLocalTable()) {
continue;
}
OlapTable olapTable = (OlapTable) table;
usedReplicaQuota = usedReplicaQuota + olapTable.getReplicaCount();
}
long leftReplicaQuota = replicaQuotaSize - usedReplicaQuota;
return Math.max(leftReplicaQuota, 0L);
} finally {
readUnlock();
}
}
public void checkDataSizeQuota() throws DdlException {
Pair<Double, String> quotaUnitPair = DebugUtil.getByteUint(dataQuotaBytes);
String readableQuota = DebugUtil.DECIMAL_FORMAT_SCALE_3.format(quotaUnitPair.first) + " "
+ quotaUnitPair.second;
long usedDataQuota = getUsedDataQuotaWithLock();
long leftDataQuota = Math.max(dataQuotaBytes - usedDataQuota, 0);
Pair<Double, String> leftQuotaUnitPair = DebugUtil.getByteUint(leftDataQuota);
String readableLeftQuota = DebugUtil.DECIMAL_FORMAT_SCALE_3.format(leftQuotaUnitPair.first) + " "
+ leftQuotaUnitPair.second;
LOG.info("database[{}] data quota: left bytes: {} / total: {}",
fullQualifiedName, readableLeftQuota, readableQuota);
if (leftDataQuota <= 0L) {
throw new DdlException("Database[" + fullQualifiedName
+ "] data size exceeds quota[" + readableQuota + "]");
}
}
public void checkReplicaQuota() throws DdlException {
long leftReplicaQuota = getReplicaQuotaLeftWithLock();
LOG.info("database[{}] replica quota: left number: {} / total: {}",
fullQualifiedName, leftReplicaQuota, replicaQuotaSize);
if (leftReplicaQuota <= 0L) {
throw new DdlException("Database[" + fullQualifiedName
+ "] replica number exceeds quota[" + replicaQuotaSize + "]");
}
}
public void checkQuota() throws DdlException {
checkDataSizeQuota();
checkReplicaQuota();
}
// return false if table already exists
public boolean createTableWithLock(Table table, boolean isReplay) {
writeLock();
try {
String tableName = table.getName();
if (nameToTable.containsKey(tableName)) {
return false;
} else {
idToTable.put(table.getId(), table);
nameToTable.put(table.getName(), table);
if (!isReplay) {
// Write edit log
CreateTableInfo info = new CreateTableInfo(fullQualifiedName, table);
GlobalStateMgr.getCurrentState().getEditLog().logCreateTable(info);
}
table.onCreate();
}
return true;
} finally {
writeUnlock();
}
}
public boolean createTable(Table table) {
boolean result = true;
String tableName = table.getName();
if (nameToTable.containsKey(tableName)) {
result = false;
} else {
idToTable.put(table.getId(), table);
nameToTable.put(table.getName(), table);
}
return result;
}
public void dropTable(String tableName, boolean isSetIfExists, boolean isForce) throws DdlException {
Table table;
HashMap<Long, AgentBatchTask> batchTaskMap;
writeLock();
try {
table = getTable(tableName);
// double check because the table may be dropped
if (table == null) {
if (isSetIfExists) {
LOG.info("drop table[{}] which does not exist", tableName);
return;
} else {
ErrorReport.reportDdlException(ErrorCode.ERR_BAD_TABLE_ERROR, tableName);
}
}
if (!isForce) {
if (GlobalStateMgr.getCurrentState().getGlobalTransactionMgr()
.existCommittedTxns(id, table.getId(), null)) {
throw new DdlException(
"There are still some transactions in the COMMITTED state waiting to be completed. " +
"The table [" + table.getName() +
"] cannot be dropped. If you want to forcibly drop(cannot be recovered)," +
" please use \"DROP table FORCE\".");
}
}
batchTaskMap = unprotectDropTable(table.getId(), isForce, false);
DropInfo info = new DropInfo(id, table.getId(), -1L, isForce);
GlobalStateMgr.getCurrentState().getEditLog().logDropTable(info);
} finally {
writeUnlock();
}
sendDropTabletTasks(batchTaskMap);
LOG.info("finished dropping table: {}, type:{} from db: {}, is force: {}",
table.getName(), table.getType(), fullQualifiedName, isForce);
}
public HashMap<Long, AgentBatchTask> unprotectDropTable(long tableId, boolean isForceDrop,
boolean isReplay) {
HashMap<Long, AgentBatchTask> batchTaskMap = new HashMap<>();
Table table = getTable(tableId);
// delete from db meta
if (table == null) {
return batchTaskMap;
}
table.onDrop();
dropTable(table.getName());
if (!isForceDrop) {
Table oldTable = GlobalStateMgr.getCurrentState().getRecycleBin().recycleTable(id, table);
if (oldTable != null && oldTable.isOlapOrLakeTable()) {
batchTaskMap = GlobalStateMgr.getCurrentState().onEraseOlapOrLakeTable((OlapTable) oldTable, isReplay);
}
} else {
if (table.isOlapOrLakeTable()) {
batchTaskMap = GlobalStateMgr.getCurrentState().onEraseOlapOrLakeTable((OlapTable) table, isReplay);
}
}
// process related materialized views
if (table.isOlapTable()) {
OlapTable olapTable = (OlapTable) table;
for (long mvId : olapTable.getRelatedMaterializedViews()) {
Table tmpTable = getTable(mvId);
if (tmpTable != null) {
MaterializedView mv = (MaterializedView) tmpTable;
mv.setActive(false);
}
}
}
LOG.info("finished dropping table[{}] in db[{}], tableId: {}", table.getName(), getFullName(),
table.getId());
return batchTaskMap;
}
public void sendDropTabletTasks(HashMap<Long, AgentBatchTask> batchTaskMap) {
int numDropTaskPerBe = Config.max_agent_tasks_send_per_be;
for (Map.Entry<Long, AgentBatchTask> entry : batchTaskMap.entrySet()) {
AgentBatchTask originTasks = entry.getValue();
if (originTasks.getTaskNum() > numDropTaskPerBe) {
AgentBatchTask partTask = new AgentBatchTask();
List<AgentTask> allTasks = originTasks.getAllTasks();
int curTask = 1;
for (AgentTask task : allTasks) {
partTask.addTask(task);
if (curTask++ > numDropTaskPerBe) {
AgentTaskExecutor.submit(partTask);
curTask = 1;
partTask = new AgentBatchTask();
ThreadUtil.sleepAtLeastIgnoreInterrupts(1000);
}
}
if (partTask.getAllTasks().size() > 0) {
AgentTaskExecutor.submit(partTask);
}
} else {
AgentTaskExecutor.submit(originTasks);
}
}
}
public void dropTableWithLock(String tableName) {
writeLock();
try {
Table table = this.nameToTable.get(tableName);
if (table != null) {
this.nameToTable.remove(tableName);
this.idToTable.remove(table.getId());
}
} finally {
writeUnlock();
}
}
public void dropTable(String tableName) {
Table table = this.nameToTable.get(tableName);
if (table != null) {
this.nameToTable.remove(tableName);
this.idToTable.remove(table.getId());
}
}
public boolean createMaterializedWithLock(MaterializedView materializedView, boolean isReplay) {
writeLock();
try {
String mvName = materializedView.getName();
if (nameToTable.containsKey(mvName)) {
return false;
} else {
idToTable.put(materializedView.getId(), materializedView);
nameToTable.put(materializedView.getName(), materializedView);
if (!isReplay) {
// Write edit log
CreateTableInfo info = new CreateTableInfo(fullQualifiedName, materializedView);
GlobalStateMgr.getCurrentState().getEditLog().logCreateMaterializedView(info);
}
materializedView.onCreate();
}
return true;
} finally {
writeUnlock();
}
}
public List<Table> getTables() {
return new ArrayList<Table>(idToTable.values());
}
public List<Table> getViews() {
List<Table> views = new ArrayList<>();
for (Table table : idToTable.values()) {
if (TableType.VIEW == table.getType()) {
views.add(table);
}
}
return views;
}
public List<Table> getMaterializedViews() {
List<Table> materializedViews = new ArrayList<>();
for (Table table : idToTable.values()) {
if (TableType.MATERIALIZED_VIEW == table.getType()) {
materializedViews.add(table);
}
}
return materializedViews;
}
public Set<String> getTableNamesWithLock() {
readLock();
try {
return new HashSet<>(this.nameToTable.keySet());
} finally {
readUnlock();
}
}
public Table getTable(String tableName) {
if (nameToTable.containsKey(tableName)) {
return nameToTable.get(tableName);
}
return null;
}
/**
* This is a thread-safe method when idToTable is a concurrent hash map
*
* @param tableId
* @return
*/
public Table getTable(long tableId) {
return idToTable.get(tableId);
}
public static Database read(DataInput in) throws IOException {
Database db = new Database();
db.readFields(in);
return db;
}
@Override
public int getSignature(int signatureVersion) {
Adler32 adler32 = new Adler32();
adler32.update(signatureVersion);
String charsetName = "UTF-8";
try {
adler32.update(this.fullQualifiedName.getBytes(charsetName));
} catch (UnsupportedEncodingException e) {
LOG.error("encoding error", e);
return -1;
}
return Math.abs((int) adler32.getValue());
}
@Override
public void write(DataOutput out) throws IOException {
super.write(out);
out.writeLong(id);
Text.writeString(out, fullQualifiedName);
// write tables
int numTables = nameToTable.size();
out.writeInt(numTables);
for (Map.Entry<String, Table> entry : nameToTable.entrySet()) {
entry.getValue().write(out);
}
out.writeLong(dataQuotaBytes);
Text.writeString(out, SystemInfoService.DEFAULT_CLUSTER);
// compatible for dbState
Text.writeString(out, "NORMAL");
// NOTE: compatible attachDbName
Text.writeString(out, "");
// write functions
out.writeInt(name2Function.size());
for (Entry<String, ImmutableList<Function>> entry : name2Function.entrySet()) {
Text.writeString(out, entry.getKey());
out.writeInt(entry.getValue().size());
for (Function function : entry.getValue()) {
function.write(out);
}
}
out.writeLong(replicaQuotaSize);
}
public void readFields(DataInput in) throws IOException {
super.readFields(in);
id = in.readLong();
if (GlobalStateMgr.getCurrentStateJournalVersion() < FeMetaVersion.VERSION_30) {
fullQualifiedName = ClusterNamespace.getFullName(Text.readString(in));
} else {
fullQualifiedName = Text.readString(in);
}
// read groups
int numTables = in.readInt();
for (int i = 0; i < numTables; ++i) {
Table table = Table.read(in);
nameToTable.put(table.getName(), table);
idToTable.put(table.getId(), table);
}
// read quota
dataQuotaBytes = in.readLong();
// Compatible for Cluster
Text.readString(in);
// Compatible for dbState
Text.readString(in);
// Compatible for attachDbName
Text.readString(in);
if (GlobalStateMgr.getCurrentStateJournalVersion() >= FeMetaVersion.VERSION_47) {
int numEntries = in.readInt();
for (int i = 0; i < numEntries; ++i) {
String name = Text.readString(in);
ImmutableList.Builder<Function> builder = ImmutableList.builder();
int numFunctions = in.readInt();
for (int j = 0; j < numFunctions; ++j) {
builder.add(Function.read(in));
}
name2Function.put(name, builder.build());
}
}
if (GlobalStateMgr.getCurrentStateJournalVersion() >= FeMetaVersion.VERSION_81) {
replicaQuotaSize = in.readLong();
} else {
replicaQuotaSize = FeConstants.default_db_replica_quota_size;
}
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Database)) {
return false;
}
Database database = (Database) obj;
if (idToTable != database.idToTable) {
if (idToTable.size() != database.idToTable.size()) {
return false;
}
for (Entry<Long, Table> entry : idToTable.entrySet()) {
long key = entry.getKey();
if (!database.idToTable.containsKey(key)) {
return false;
}
if (!entry.getValue().equals(database.idToTable.get(key))) {
return false;
}
}
}
return (id == database.id) && (fullQualifiedName.equals(database.fullQualifiedName)
&& dataQuotaBytes == database.dataQuotaBytes);
}
public void setName(String name) {
this.fullQualifiedName = name;
}
public synchronized void addFunction(Function function) throws UserException {
addFunctionImpl(function, false);
GlobalStateMgr.getCurrentState().getEditLog().logAddFunction(function);
}
public synchronized void replayAddFunction(Function function) {
try {
addFunctionImpl(function, true);
} catch (UserException e) {
Preconditions.checkArgument(false);
}
}
public static void replayCreateFunctionLog(Function function) {
String dbName = function.getFunctionName().getDb();
Database db = GlobalStateMgr.getCurrentState().getDb(dbName);
if (db == null) {
throw new Error("unknown database when replay log, db=" + dbName);
}
db.replayAddFunction(function);
}
// return true if add success, false
private void addFunctionImpl(Function function, boolean isReplay) throws UserException {
String functionName = function.getFunctionName().getFunction();
List<Function> existFuncs = name2Function.get(functionName);
if (!isReplay) {
if (existFuncs != null) {
for (Function existFunc : existFuncs) {
if (function.compare(existFunc, Function.CompareMode.IS_IDENTICAL)) {
throw new UserException("function already exists");
}
}
}
// Get function id for this UDF, use CatalogIdGenerator. Only get function id
// when isReplay is false
long functionId = GlobalStateMgr.getCurrentState().getNextId();
// all user-defined functions id are negative to avoid conflicts with the builtin function
function.setFunctionId(-functionId);
}
ImmutableList.Builder<Function> builder = ImmutableList.builder();
if (existFuncs != null) {
builder.addAll(existFuncs);
}
builder.add(function);
name2Function.put(functionName, builder.build());
}
public synchronized void dropFunction(FunctionSearchDesc function) throws UserException {
dropFunctionImpl(function);
GlobalStateMgr.getCurrentState().getEditLog().logDropFunction(function);
}
public synchronized void replayDropFunction(FunctionSearchDesc functionSearchDesc) {
try {
dropFunctionImpl(functionSearchDesc);
} catch (UserException e) {
Preconditions.checkArgument(false);
}
}
public static void replayDropFunctionLog(FunctionSearchDesc functionSearchDesc) {
String dbName = functionSearchDesc.getName().getDb();
Database db = GlobalStateMgr.getCurrentState().getDb(dbName);
if (db == null) {
throw new Error("unknown database when replay log, db=" + dbName);
}
db.replayDropFunction(functionSearchDesc);
}
private void dropFunctionImpl(FunctionSearchDesc function) throws UserException {
String functionName = function.getName().getFunction();
List<Function> existFuncs = name2Function.get(functionName);
if (existFuncs == null) {
throw new UserException("Unknown function, function=" + function.toString());
}
boolean isFound = false;
ImmutableList.Builder<Function> builder = ImmutableList.builder();
for (Function existFunc : existFuncs) {
if (function.isIdentical(existFunc)) {
isFound = true;
} else {
builder.add(existFunc);
}
}
if (!isFound) {
throw new UserException("Unknown function, function=" + function.toString());
}
ImmutableList<Function> newFunctions = builder.build();
if (newFunctions.isEmpty()) {
name2Function.remove(functionName);
} else {
name2Function.put(functionName, newFunctions);
}
}
public synchronized Function getFunction(Function desc, Function.CompareMode mode) {
List<Function> fns = name2Function.get(desc.getFunctionName().getFunction());
if (fns == null) {
return null;
}
return Function.getFunction(fns, desc, mode);
}
public synchronized List<Function> getFunctions() {
List<Function> functions = Lists.newArrayList();
for (Map.Entry<String, ImmutableList<Function>> entry : name2Function.entrySet()) {
functions.addAll(entry.getValue());
}
return functions;
}
public boolean isInfoSchemaDb() {
return ClusterNamespace.getNameFromFullName(fullQualifiedName).equalsIgnoreCase(InfoSchemaDb.DATABASE_NAME);
}
}