/
Database.java
2461 lines (2201 loc) · 75.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
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
/*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.lealone.db;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
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 org.lealone.api.DatabaseEventListener;
import org.lealone.api.ErrorCode;
import org.lealone.common.exceptions.DbException;
import org.lealone.common.trace.Trace;
import org.lealone.common.trace.TraceSystem;
import org.lealone.common.util.BitField;
import org.lealone.common.util.MathUtils;
import org.lealone.common.util.New;
import org.lealone.common.util.ShutdownHookUtils;
import org.lealone.common.util.SmallLRUCache;
import org.lealone.common.util.StatementBuilder;
import org.lealone.common.util.StringUtils;
import org.lealone.common.util.TempFileDeleter;
import org.lealone.common.util.Utils;
import org.lealone.db.auth.Right;
import org.lealone.db.auth.Role;
import org.lealone.db.auth.User;
import org.lealone.db.constraint.Constraint;
import org.lealone.db.index.Cursor;
import org.lealone.db.index.Index;
import org.lealone.db.index.IndexType;
import org.lealone.db.result.Row;
import org.lealone.db.result.SearchRow;
import org.lealone.db.schema.Schema;
import org.lealone.db.schema.SchemaObject;
import org.lealone.db.schema.Sequence;
import org.lealone.db.schema.TriggerObject;
import org.lealone.db.table.Column;
import org.lealone.db.table.CreateTableData;
import org.lealone.db.table.IndexColumn;
import org.lealone.db.table.MetaTable;
import org.lealone.db.table.Table;
import org.lealone.db.table.TableAlterHistoryRecord;
import org.lealone.db.table.TableView;
import org.lealone.db.util.SourceCompiler;
import org.lealone.db.value.CaseInsensitiveMap;
import org.lealone.db.value.CompareMode;
import org.lealone.db.value.Value;
import org.lealone.db.value.ValueInt;
import org.lealone.net.NetEndpoint;
import org.lealone.sql.SQLEngine;
import org.lealone.sql.SQLEngineManager;
import org.lealone.sql.SQLParser;
import org.lealone.storage.LobStorage;
import org.lealone.storage.Storage;
import org.lealone.storage.StorageBuilder;
import org.lealone.storage.StorageEngine;
import org.lealone.storage.fs.FileStorage;
import org.lealone.storage.fs.FileUtils;
import org.lealone.storage.memory.MemoryStorageEngine;
import org.lealone.transaction.TransactionEngine;
import org.lealone.transaction.TransactionEngineManager;
/**
* There is one database object per open database.
*
* @author H2 Group
* @author zhh
*/
public class Database implements DataHandler, DbObject {
/**
* The default name of the system user. This name is only used as long as
* there is no administrator user registered.
*/
private static final String SYSTEM_USER_NAME = "DBA";
private final HashMap<String, User> users = New.hashMap();
private final HashMap<String, Role> roles = New.hashMap();
private final HashMap<String, Right> rights = New.hashMap();
private final HashMap<String, UserDataType> userDataTypes = New.hashMap();
private final HashMap<String, UserAggregate> aggregates = New.hashMap();
private final HashMap<String, Setting> settings = New.hashMap();
private final HashMap<String, Comment> comments = New.hashMap();
private final HashMap<String, Schema> schemas = New.hashMap();
// 与users、roles和rights相关的操作都用这个对象进行同步
private final Object authLock = new Object();
public Object getAuthLock() {
return authLock;
}
private final Set<ServerSession> userSessions = Collections.synchronizedSet(new HashSet<ServerSession>());
private ServerSession exclusiveSession;
private final BitField objectIds = new BitField();
private final Object lobSyncObject = new Object();
private Schema mainSchema;
private Schema infoSchema;
private int nextSessionId;
private int nextTempTableId;
private User systemUser;
private SystemSession systemSession;
private Table meta;
private Index metaIdIndex;
private boolean starting;
private TraceSystem traceSystem;
private Trace trace;
private Role publicRole;
private long modificationDataId;
private long modificationMetaId;
private CompareMode compareMode;
private boolean readOnly;
private int writeDelay = Constants.DEFAULT_WRITE_DELAY;
private DatabaseEventListener eventListener;
private int maxMemoryRows = Constants.DEFAULT_MAX_MEMORY_ROWS;
private int maxMemoryUndo = Constants.DEFAULT_MAX_MEMORY_UNDO;
private int lockMode = Constants.DEFAULT_LOCK_MODE;
private int maxLengthInplaceLob;
private int allowLiterals = Constants.ALLOW_LITERALS_ALL;
private int powerOffCount;
private int closeDelay = -1; // 不关闭
private DatabaseCloser delayedCloser;
private volatile boolean closing;
private boolean ignoreCase;
private boolean deleteFilesOnDisconnect;
private String lobCompressionAlgorithm;
private boolean optimizeReuseResults = true;
private boolean referentialIntegrity = true;
private final boolean multiVersion;
private DatabaseCloser closeOnExit;
private Mode mode = Mode.getDefaultMode();
private int maxOperationMemory = Constants.DEFAULT_MAX_OPERATION_MEMORY;
private SmallLRUCache<String, String[]> lobFileListCache;
private final TempFileDeleter tempFileDeleter = TempFileDeleter.getInstance();
private int cacheSize;
private int compactMode;
private SourceCompiler compiler;
private volatile boolean metaTablesInitialized;
private LobStorage lobStorage;
private int defaultTableType = Table.TYPE_CACHED;
private volatile boolean initialized = false;
private DbException backgroundException;
private boolean queryStatistics;
private int queryStatisticsMaxEntries = Constants.QUERY_STATISTICS_MAX_ENTRIES;
private QueryStatisticsData queryStatisticsData;
private final int id;
private final String name;
private final Map<String, String> parameters;
private final DbSettings dbSettings;
private final boolean persistent;
// 每个数据库只有一个SQL引擎和一个事务引擎
private final SQLEngine sqlEngine;
private final TransactionEngine transactionEngine;
private String storageName; // 不使用原始的名称,而是用id替换数据库名
private Map<String, String> replicationProperties;
private ReplicationPropertiesChangeListener replicationPropertiesChangeListener;
private RunMode runMode = RunMode.CLIENT_SERVER;
public Database(int id, String name, Map<String, String> parameters) {
this.id = id;
this.name = name;
this.storageName = getStorageName();
this.parameters = parameters;
if (parameters != null)
dbSettings = DbSettings.getInstance(parameters);
else
dbSettings = DbSettings.getDefaultSettings();
persistent = dbSettings.persistent;
compareMode = CompareMode.getInstance(null, 0, false);
if (dbSettings.mode != null) {
mode = Mode.getInstance(dbSettings.mode);
}
maxLengthInplaceLob = SysProperties.LOB_IN_DATABASE ? Constants.DEFAULT_MAX_LENGTH_INPLACE_LOB2
: Constants.DEFAULT_MAX_LENGTH_INPLACE_LOB;
cacheSize = dbSettings.cacheSize;
String engineName = dbSettings.defaultSQLEngine;
SQLEngine sqlEngine = SQLEngineManager.getInstance().getEngine(engineName);
if (sqlEngine == null) {
try {
sqlEngine = (SQLEngine) Utils.loadUserClass(engineName).newInstance();
SQLEngineManager.getInstance().registerEngine(sqlEngine);
} catch (Exception e) {
e = new RuntimeException("Fatal error: the sql engine '" + engineName + "' not found", e);
throw DbException.convert(e);
}
}
this.sqlEngine = sqlEngine;
engineName = dbSettings.defaultTransactionEngine;
TransactionEngine transactionEngine = TransactionEngineManager.getInstance().getEngine(engineName);
if (transactionEngine == null) {
try {
transactionEngine = (TransactionEngine) Utils.loadUserClass(engineName).newInstance();
TransactionEngineManager.getInstance().registerEngine(transactionEngine);
} catch (Exception e) {
e = new RuntimeException("Fatal error: the transaction engine '" + engineName + "' not found", e);
throw DbException.convert(e);
}
}
this.transactionEngine = transactionEngine;
multiVersion = transactionEngine.supportsMVCC();
}
@Override
public int getId() {
return id;
}
@Override
public String getName() {
return name;
}
public String getShortName() {
return getName();
}
public DbSettings getSettings() {
return dbSettings;
}
public boolean isPersistent() {
return persistent;
}
public SQLEngine getSQLEngine() {
return sqlEngine;
}
public TransactionEngine getTransactionEngine() {
return transactionEngine;
}
public SQLParser createParser(Session session) {
return sqlEngine.createParser(session);
}
public String quoteIdentifier(String identifier) {
return sqlEngine.quoteIdentifier(identifier);
}
public String getDefaultStorageEngineName() {
return dbSettings.defaultStorageEngine;
}
public Map<String, String> getReplicationProperties() {
return replicationProperties;
}
public void setReplicationProperties(Map<String, String> replicationProperties) {
this.replicationProperties = replicationProperties;
if (replicationPropertiesChangeListener != null)
replicationPropertiesChangeListener.replicationPropertiesChanged(this);
}
public void setReplicationPropertiesChangeListener(ReplicationPropertiesChangeListener listener) {
replicationPropertiesChangeListener = listener;
}
public static interface ReplicationPropertiesChangeListener {
void replicationPropertiesChanged(Database db);
}
public void setRunMode(RunMode runMode) {
if (runMode != null && this.runMode != runMode) {
this.runMode = runMode;
}
}
public RunMode getRunMode() {
return runMode;
}
public Map<String, String> getParameters() {
return parameters;
}
public boolean isShardingMode() {
return runMode == RunMode.SHARDING;
}
public synchronized Database copy() {
Database db = new Database(id, name, parameters);
// 因为每个存储只能打开一次,所以要复用原有存储
db.storageName = storageName;
db.storageBuilder = storageBuilder;
db.storages.putAll(storages);
db.init();
LealoneDatabase.getInstance().getDatabasesMap().put(name, db);
for (ServerSession s : userSessions) {
db.userSessions.add(s);
s.setDatabase(db);
}
return db;
}
public boolean isInitialized() {
return initialized;
}
public synchronized void init() {
if (initialized)
return;
initialized = true;
String listener = dbSettings.eventListener;
if (listener != null) {
listener = StringUtils.trim(listener, true, true, "'");
setEventListenerClass(listener);
}
initTraceSystem();
openDatabase();
addShutdownHook();
initDbObjectVersionTable();
opened();
}
private void initTraceSystem() {
if (persistent) {
traceSystem = new TraceSystem(getStorageName() + Constants.SUFFIX_TRACE_FILE);
traceSystem.setLevelFile(dbSettings.traceLevelFile);
traceSystem.setLevelSystemOut(dbSettings.traceLevelSystemOut);
trace = traceSystem.getTrace(Trace.DATABASE);
trace.info("opening {0} (build {1})", name, Constants.BUILD_ID);
} else {
traceSystem = new TraceSystem();
trace = traceSystem.getTrace(Trace.DATABASE);
}
}
private void addShutdownHook() {
if (dbSettings.dbCloseOnExit) {
try {
closeOnExit = new DatabaseCloser(this, 0, true);
ShutdownHookUtils.addShutdownHook(closeOnExit);
} catch (IllegalStateException | SecurityException e) {
// shutdown in progress - just don't register the handler
// (maybe an application wants to write something into a
// database at shutdown time)
}
}
}
private void openDatabase() {
try {
// 初始化traceSystem后才能做下面这些
systemUser = new User(this, 0, SYSTEM_USER_NAME, true);
systemUser.setAdmin(true);
publicRole = new Role(this, 0, Constants.PUBLIC_ROLE_NAME, true);
roles.put(Constants.PUBLIC_ROLE_NAME, publicRole);
mainSchema = new Schema(this, 0, Constants.SCHEMA_MAIN, systemUser, true);
infoSchema = new Schema(this, -1, "INFORMATION_SCHEMA", systemUser, true);
schemas.put(mainSchema.getName(), mainSchema);
schemas.put(infoSchema.getName(), infoSchema);
systemSession = new SystemSession(this, systemUser, ++nextSessionId);
// long t1 = System.currentTimeMillis();
openMetaTable();
// System.out.println(getShortName() + ": openMetaTable total time: " + (System.currentTimeMillis() - t1)
// + " ms");
if (!readOnly) {
// set CREATE_BUILD in a new database
String name = SetTypes.getTypeName(SetTypes.CREATE_BUILD);
if (!settings.containsKey(name)) {
Setting setting = new Setting(this, allocateObjectId(), name);
setting.setIntValue(Constants.BUILD_ID);
lockMeta(systemSession);
addDatabaseObject(systemSession, setting);
}
}
systemSession.commit();
trace.info("opened {0}", name);
} catch (Throwable e) {
if (e instanceof OutOfMemoryError) {
e.fillInStackTrace();
}
if (traceSystem != null) {
if (e instanceof SQLException) {
SQLException e2 = (SQLException) e;
if (e2.getErrorCode() != ErrorCode.DATABASE_ALREADY_OPEN_1) {
// only write if the database is not already in use
trace.error(e, "opening {0}", name);
}
}
traceSystem.close();
}
closeOpenFilesAndUnlock(false);
throw DbException.convert(e);
}
}
private void openMetaTable() {
CreateTableData data = new CreateTableData();
ArrayList<Column> cols = data.columns;
Column columnId = new Column("ID", Value.INT);
columnId.setNullable(false);
cols.add(columnId);
cols.add(new Column("TYPE", Value.INT));
cols.add(new Column("SQL", Value.STRING));
data.tableName = "SYS";
data.id = 0;
data.persistData = persistent;
data.persistIndexes = persistent;
data.create = true;
data.isHidden = true;
data.session = systemSession;
meta = mainSchema.createTable(data);
IndexColumn[] pkCols = IndexColumn.wrap(new Column[] { columnId });
IndexType indexType = IndexType.createDelegate(); // 重用原有的primary index
metaIdIndex = meta.addIndex(systemSession, "SYS_ID", 0, pkCols, indexType, true, null);
ArrayList<MetaRecord> records = New.arrayList();
Cursor cursor = metaIdIndex.find(systemSession, null, null);
while (cursor.next()) {
MetaRecord rec = new MetaRecord(cursor.get());
objectIds.set(rec.getId());
records.add(rec);
}
objectIds.set(0);
starting = true;
Collections.sort(records);
for (MetaRecord rec : records) {
rec.execute(this, systemSession, eventListener);
}
recompileInvalidViews();
starting = false;
}
public synchronized void rollbackMetaTable(ServerSession session) {
ArrayList<MetaRecord> records = New.arrayList();
Cursor cursor = metaIdIndex.find(systemSession, null, null);
while (cursor.next()) {
MetaRecord rec = new MetaRecord(cursor.get());
objectIds.set(rec.getId());
records.add(rec);
}
objectIds.set(0);
starting = true;
Collections.sort(records);
for (MetaRecord rec : records) {
rec.execute(this, systemSession, eventListener);
}
recompileInvalidViews();
starting = false;
}
private void recompileInvalidViews() {
boolean recompileSuccessful;
do {
recompileSuccessful = false;
for (Table obj : getAllTablesAndViews(false)) {
if (obj instanceof TableView) {
TableView view = (TableView) obj;
if (view.isInvalid()) { // 这里是无效的要recompile
view.recompile(systemSession, true);
if (!view.isInvalid()) {
recompileSuccessful = true;
}
}
}
}
} while (recompileSuccessful);
// when opening a database, views are initialized before indexes,
// so they may not have the optimal plan yet
// this is not a problem, it is just nice to see the newest plan
for (Table obj : getAllTablesAndViews(false)) {
if (obj instanceof TableView) {
TableView view = (TableView) obj;
if (!view.isInvalid()) { // 这里是有效的要recompile
view.recompile(systemSession, true);
}
}
}
}
/**
* Check if two values are equal with the current comparison mode.
*
* @param a the first value
* @param b the second value
* @return true if both objects are equal
*/
public boolean areEqual(Value a, Value b) {
// can not use equals because ValueDecimal 0.0 is not equal to 0.00.
return a.compareTo(b, compareMode) == 0;
}
/**
* Compare two values with the current comparison mode. The values may not
* be of the same type.
*
* @param a the first value
* @param b the second value
* @return 0 if both values are equal, -1 if the first value is smaller, and
* 1 otherwise
*/
public int compare(Value a, Value b) {
return a.compareTo(b, compareMode);
}
/**
* Compare two values with the current comparison mode. The values must be
* of the same type.
*
* @param a the first value
* @param b the second value
* @return 0 if both values are equal, -1 if the first value is smaller, and
* 1 otherwise
*/
public int compareTypeSafe(Value a, Value b) {
return a.compareTypeSafe(b, compareMode);
}
public long getModificationDataId() {
return modificationDataId;
}
public long getNextModificationDataId() {
return ++modificationDataId;
}
public long getModificationMetaId() {
return modificationMetaId;
}
public long getNextModificationMetaId() {
// if the meta data has been modified, the data is modified as well
// (because MetaTable returns modificationDataId)
modificationDataId++;
return modificationMetaId++;
}
public void setPowerOffCount(int count) {
if (powerOffCount == -1) {
return;
}
powerOffCount = count;
}
public int getPowerOffCount() {
return powerOffCount;
}
@Override
public void checkPowerOff() {
if (powerOffCount == 0) {
return;
}
if (powerOffCount > 1) {
powerOffCount--;
return;
}
if (powerOffCount != -1) {
try {
powerOffCount = -1;
for (Storage s : getStorages()) {
s.closeImmediately();
}
if (traceSystem != null) {
traceSystem.close();
}
} catch (DbException e) {
DbException.traceThrowable(e);
}
}
LealoneDatabase.getInstance().closeDatabase(name);
throw DbException.get(ErrorCode.DATABASE_IS_CLOSED);
}
/**
* Get the trace object for the given module id.
*
* @param moduleId the module id
* @return the trace object
*/
public Trace getTrace(int moduleId) {
return traceSystem.getTrace(moduleId);
}
@Override
public FileStorage openFile(String name, String openMode, boolean mustExist) {
if (mustExist && !FileUtils.exists(name)) {
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, name);
}
FileStorage fileStorage = FileStorage.open(this, name, openMode, dbSettings.cipher,
dbSettings.filePasswordHash);
try {
fileStorage.init();
} catch (DbException e) {
fileStorage.closeSilently();
throw e;
}
return fileStorage;
}
/**
* Check if the file password hash is correct.
*
* @param testCipher the cipher algorithm
* @param testHash the hash code
* @return true if the cipher algorithm and the password match
*/
boolean validateFilePasswordHash(String testCipher, byte[] testHash) {
if (!StringUtils.equals(testCipher, dbSettings.cipher)) {
return false;
}
return Utils.compareSecure(testHash, dbSettings.filePasswordHash);
}
private void initMetaTables() {
if (metaTablesInitialized) {
return;
}
synchronized (infoSchema) {
if (!metaTablesInitialized) {
for (int type = 0, count = MetaTable.getMetaTableTypeCount(); type < count; type++) {
MetaTable m = new MetaTable(infoSchema, -1 - type, type);
infoSchema.add(m);
}
metaTablesInitialized = true;
}
}
}
/**
* Checks if the system table (containing the catalog) is locked.
*
* @return true if it is currently locked
*/
public boolean isSysTableLocked() {
return meta == null || meta.isLockedExclusively();
}
public boolean isSysTableLockedBy(ServerSession session) {
return meta == null || meta.isLockedExclusivelyBy(session);
}
/**
* Verify the meta table is locked.
*
* @param session the session
*/
public void verifyMetaLocked(ServerSession session) {
if (!lockMeta(session) && lockMode != 0) {
throw DbException.throwInternalError();
}
}
/**
* Lock the metadata table for updates.
*
* @param session the session
* @return whether it was already locked before by this session
*/
public boolean lockMeta(ServerSession session) {
return false;
}
public void unlockMeta(ServerSession session) {
meta.unlock(session);
}
private Cursor getMetaCursor(ServerSession session, int id) {
SearchRow r = meta.getTemplateSimpleRow(false);
r.setValue(0, ValueInt.get(id));
return metaIdIndex.find(session, r, r);
}
// 用于测试
public SearchRow findMeta(ServerSession session, int id) {
Cursor cursor = getMetaCursor(session, id);
cursor.next();
return cursor.getSearchRow();
}
@SuppressWarnings("unchecked")
private Map<String, DbObject> getMap(DbObjectType type) {
Map<String, ? extends DbObject> result;
switch (type) {
case USER:
result = users;
break;
case SETTING:
result = settings;
break;
case ROLE:
result = roles;
break;
case RIGHT:
result = rights;
break;
case SCHEMA:
result = schemas;
break;
case USER_DATATYPE:
result = userDataTypes;
break;
case COMMENT:
result = comments;
break;
case AGGREGATE:
result = aggregates;
break;
case DATABASE:
result = LealoneDatabase.getInstance().getDatabasesMap();
break;
default:
throw DbException.throwInternalError("type=" + type);
}
return (Map<String, DbObject>) result;
}
public Object getLock(DbObjectType type) {
Object lock;
switch (type) {
case USER:
lock = authLock;
break;
case SETTING:
lock = settings;
break;
case ROLE:
lock = authLock;
break;
case RIGHT:
lock = rights;
break;
case SCHEMA:
lock = schemas;
break;
case USER_DATATYPE:
lock = userDataTypes;
break;
case COMMENT:
lock = comments;
break;
case AGGREGATE:
lock = aggregates;
break;
case DATABASE:
lock = LealoneDatabase.getInstance().getDatabasesMap();
break;
default:
throw DbException.throwInternalError("type=" + type);
}
return lock;
}
/**
* Add a schema object to the database.
*
* @param session the session
* @param obj the object to add
*/
public void addSchemaObject(ServerSession session, SchemaObject obj) {
int id = obj.getId();
if (id > 0 && !starting) {
checkWritingAllowed();
}
// lockMeta(session);
obj.getSchema().add(obj);
addMeta(session, obj);
}
private void addMeta(ServerSession session, DbObject obj) {
int id = obj.getId();
if (id > 0 && !starting && !obj.isTemporary()) {
Row r = meta.getTemplateRow();
MetaRecord rec = new MetaRecord(obj);
rec.setRecord(r);
synchronized (objectIds) {
objectIds.set(id);
}
// if (SysProperties.CHECK) {
// verifyMetaLocked(session);
// }
meta.addRow(session, r);
}
}
private void updateMetaAndFirstLevelChildren(ServerSession session, DbObject obj) {
List<DbObject> list = obj.getChildren();
Comment comment = findComment(obj);
if (comment != null) {
DbException.throwInternalError();
}
updateMeta(session, obj);
// remember that this scans only one level deep!
if (list != null) {
for (DbObject o : list) {
if (o.getCreateSQL() != null) {
updateMeta(session, o);
}
}
}
}
/**
* Remove the given object from the meta data.
*
* @param session the session
* @param id the id of the object to remove
*/
public void removeMeta(ServerSession session, int id) {
if (id > 0 && !starting) {
SearchRow r = meta.getTemplateSimpleRow(false);
r.setValue(0, ValueInt.get(id));
Cursor cursor = metaIdIndex.find(session, r, r);
if (cursor.next()) {
Row found = cursor.get();
meta.removeRow(session, found);
synchronized (objectIds) {
objectIds.clear(id);
}
}
}
}
/**
* Update an object in the system table.
*
* @param session the session
* @param obj the database object
*/
public void updateMeta(ServerSession session, DbObject obj) {
// lockMeta(session);
int id = obj.getId();
removeMeta(session, id);
addMeta(session, obj);
}
/**
* Add an object to the database.
*
* @param session the session
* @param obj the object to add
*/
public void addDatabaseObject(ServerSession session, DbObject obj) {
int id = obj.getId();
if (id > 0 && !starting) {
checkWritingAllowed();
}
DbObjectType type = obj.getType();
synchronized (getLock(type)) {
Map<String, DbObject> map = getMap(type);
String name = obj.getName();
if (SysProperties.CHECK && map.get(name) != null) {
DbException.throwInternalError("object already exists");
}
// lockMeta(session);
addMeta(session, obj);
map.put(name, obj);
}
}
/**
* Get the user defined aggregate function if it exists, or null if not.
*
* @param name the name of the user defined aggregate function
* @return the aggregate function or null
*/
public UserAggregate findAggregate(String name) {
return aggregates.get(name);
}
/**
* Get the comment for the given database object if one exists, or null if
* not.
*
* @param object the database object
* @return the comment or null
*/
public Comment findComment(DbObject object) {
if (object.getType() == DbObjectType.COMMENT) {
return null;
}
String key = Comment.getKey(object);
return comments.get(key);
}
/**
* Get the role if it exists, or null if not.
*
* @param roleName the name of the role
* @return the role or null
*/
public Role findRole(String roleName) {
synchronized (getAuthLock()) {
return roles.get(roleName);
}
}
/**
* Get the schema if it exists, or null if not.
*
* @param schemaName the name of the schema
* @return the schema or null
*/
public Schema findSchema(String schemaName) {
Schema schema = schemas.get(schemaName);
if (schema == infoSchema) {
initMetaTables();
}
return schema;
}
/**
* Get the setting if it exists, or null if not.
*
* @param name the name of the setting
* @return the setting or null
*/
public Setting findSetting(String name) {
return settings.get(name);
}
/**
* Get the user if it exists, or null if not.
*
* @param name the name of the user
* @return the user or null
*/
public User findUser(String name) {
synchronized (getAuthLock()) {
return users.get(name);
}
}
/**
* Get the user defined data type if it exists, or null if not.
*
* @param name the name of the user defined data type
* @return the user defined data type or null
*/
public UserDataType findUserDataType(String name) {
return userDataTypes.get(name);
}
/**
* Get user with the given name. This method throws an exception if the user
* does not exist.
*
* @param name the user name
* @return the user
* @throws DbException if the user does not exist
*/
public User getUser(String name) {
User user = findUser(name);
if (user == null) {
throw DbException.get(ErrorCode.USER_NOT_FOUND_1, name);
}
return user;
}
/**
* Create a session for the given user.
*
* @param user the user
* @return the session
* @throws DbException if the database is in exclusive mode
*/