Debian Codegraph @

lang/java/src/com/sleepycat/persist/impl/Store.java

raw
1 /*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2002, 2013 Oracle and/or its affiliates. All rights reserved.
5 *
6 */
7
8 package com.sleepycat.persist.impl;
9
10 import java.util.ArrayList;
11 import java.util.Comparator;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.WeakHashMap;
18
19 import com.sleepycat.bind.EntityBinding;
20 import com.sleepycat.bind.tuple.StringBinding;
21 import com.sleepycat.compat.DbCompat;
22 import com.sleepycat.db.Cursor;
23 import com.sleepycat.db.CursorConfig;
24 import com.sleepycat.db.Database;
25 import com.sleepycat.db.DatabaseConfig;
26 import com.sleepycat.db.DatabaseEntry;
27 import com.sleepycat.db.DatabaseException;
28 import com.sleepycat.db.Environment;
29 import com.sleepycat.db.ForeignKeyDeleteAction;
30 import com.sleepycat.db.OperationStatus;
31 import com.sleepycat.db.SecondaryConfig;
32 import com.sleepycat.db.SecondaryDatabase;
33 import com.sleepycat.db.Sequence;
34 import com.sleepycat.db.SequenceConfig;
35 import com.sleepycat.db.Transaction;
36 import com.sleepycat.db.TransactionConfig;
37 import java.util.IdentityHashMap;
38 import com.sleepycat.persist.DatabaseNamer;
39 import com.sleepycat.persist.IndexNotAvailableException;
40 import com.sleepycat.persist.PrimaryIndex;
41 import com.sleepycat.persist.SecondaryIndex;
42 import com.sleepycat.persist.StoreConfig;
43 import com.sleepycat.persist.StoreExistsException;
44 import com.sleepycat.persist.StoreNotFoundException;
45 import com.sleepycat.persist.evolve.EvolveConfig;
46 import com.sleepycat.persist.evolve.EvolveEvent;
47 import com.sleepycat.persist.evolve.EvolveInternal;
48 import com.sleepycat.persist.evolve.EvolveListener;
49 import com.sleepycat.persist.evolve.EvolveStats;
50 import com.sleepycat.persist.evolve.IncompatibleClassException;
51 import com.sleepycat.persist.evolve.Mutations;
52 import com.sleepycat.persist.model.DeleteAction;
53 import com.sleepycat.persist.model.EntityMetadata;
54 import com.sleepycat.persist.model.EntityModel;
55 import com.sleepycat.persist.model.PrimaryKeyMetadata;
56 import com.sleepycat.persist.model.Relationship;
57 import com.sleepycat.persist.model.SecondaryKeyMetadata;
58 import com.sleepycat.persist.raw.RawObject;
59 import com.sleepycat.util.keyrange.KeyRange;
60 import com.sleepycat.util.RuntimeExceptionWrapper;
61
62 /**
63 * Base implementation for EntityStore and RawStore. The methods here
64 * correspond directly to those in EntityStore; see EntityStore documentation
65 * for details.
66 *
67 * @author Mark Hayes
68 */
69 public class Store {
70
71 public static final String NAME_SEPARATOR = "#";
72 private static final String NAME_PREFIX = "persist" + NAME_SEPARATOR;
73 private static final String DB_NAME_PREFIX = "com.sleepycat.persist.";
74 private static final String CATALOG_DB = DB_NAME_PREFIX + "formats";
75 private static final String SEQUENCE_DB = DB_NAME_PREFIX + "sequences";
76
77 private static Map<Environment, Map<String, PersistCatalog>> catalogPool =
78 new WeakHashMap<Environment, Map<String, PersistCatalog>>();
79
80 /* For unit testing. */
81 private static SyncHook syncHook;
82 public static boolean expectFlush;
83
84 private final Environment env;
85 private final boolean rawAccess;
86 private volatile PersistCatalog catalog;
87 private EntityModel model;
88 private final StoreConfig storeConfig;
89 private final String storeName;
90 private final String storePrefix;
91 private final Map<String, InternalPrimaryIndex> priIndexMap;
92 private final Map<String, InternalSecondaryIndex> secIndexMap;
93 private final Map<String, DatabaseConfig> priConfigMap;
94 private final Map<String, SecondaryConfig> secConfigMap;
95 private final Map<String, PersistKeyBinding> keyBindingMap;
96 private Database sequenceDb;
97 private final Map<String, Sequence> sequenceMap;
98 private final Map<String, SequenceConfig> sequenceConfigMap;
99 private final IdentityHashMap<Database, Object> deferredWriteDatabases;
100 private final Map<String, Set<String>> inverseRelatedEntityMap;
101 private final TransactionConfig autoCommitTxnConfig;
102 private final TransactionConfig autoCommitNoWaitTxnConfig;
103
104 public Store(Environment env,
105 String storeName,
106 StoreConfig config,
107 boolean rawAccess)
108 throws StoreExistsException,
109 StoreNotFoundException,
110 IncompatibleClassException,
111 DatabaseException {
112
113 this.env = env;
114 this.storeName = storeName;
115 this.rawAccess = rawAccess;
116
117 if (env == null || storeName == null) {
118 throw new NullPointerException
119 ("env and storeName parameters must not be null");
120 }
121
122 storeConfig = (config != null) ?
123 config.clone() :
124 StoreConfig.DEFAULT;
125
126 autoCommitTxnConfig = new TransactionConfig();
127 autoCommitNoWaitTxnConfig = new TransactionConfig();
128 autoCommitNoWaitTxnConfig.setNoWait(true);
129
130 model = config.getModel();
131
132 storePrefix = NAME_PREFIX + storeName + NAME_SEPARATOR;
133 priIndexMap = new HashMap<String, InternalPrimaryIndex>();
134 secIndexMap = new HashMap<String, InternalSecondaryIndex>();
135 priConfigMap = new HashMap<String, DatabaseConfig>();
136 secConfigMap = new HashMap<String, SecondaryConfig>();
137 keyBindingMap = new HashMap<String, PersistKeyBinding>();
138 sequenceMap = new HashMap<String, Sequence>();
139 sequenceConfigMap = new HashMap<String, SequenceConfig>();
140 deferredWriteDatabases = new IdentityHashMap<Database, Object>();
141
142 if (rawAccess) {
143 /* Open a read-only catalog that uses the stored model. */
144 if (model != null) {
145 throw new IllegalArgumentException
146 ("A model may not be specified when opening a RawStore");
147 }
148 DatabaseConfig dbConfig = new DatabaseConfig();
149 dbConfig.setReadOnly(true);
150 dbConfig.setTransactional
151 (storeConfig.getTransactional());
152 catalog = new PersistCatalog
153 (env, storePrefix, storePrefix + CATALOG_DB, dbConfig,
154 null /*model*/, config.getMutations(), rawAccess, this);
155 } else {
156 /* Open the shared catalog that uses the current model. */
157 synchronized (catalogPool) {
158 Map<String, PersistCatalog> catalogMap = catalogPool.get(env);
159 if (catalogMap == null) {
160 catalogMap = new HashMap<String, PersistCatalog>();
161 catalogPool.put(env, catalogMap);
162 }
163 catalog = catalogMap.get(storeName);
164 if (catalog != null) {
165 catalog.openExisting();
166 } else {
167 DatabaseConfig dbConfig = new DatabaseConfig();
168 dbConfig.setAllowCreate(storeConfig.getAllowCreate());
169 dbConfig.setExclusiveCreate
170 (storeConfig.getExclusiveCreate());
171 dbConfig.setReadOnly(storeConfig.getReadOnly());
172 dbConfig.setTransactional
173 (storeConfig.getTransactional());
174 DbCompat.setTypeBtree(dbConfig);
175 catalog = new PersistCatalog
176 (env, storePrefix, storePrefix + CATALOG_DB, dbConfig,
177 model, config.getMutations(), rawAccess, this);
178 catalogMap.put(storeName, catalog);
179 }
180 }
181 }
182
183 /*
184 * If there is no model parameter, use the default or stored model
185 * obtained from the catalog.
186 */
187 model = catalog.getResolvedModel();
188
189 /*
190 * For each existing entity with a relatedEntity reference, create an
191 * inverse map (back pointer) from the class named in the relatedEntity
192 * to the class containing the secondary key. This is used to open the
193 * class containing the secondary key whenever we open the
194 * relatedEntity class, to configure foreign key constraints. Note that
195 * we do not need to update this map as new primary indexes are
196 * created, because opening the new index will setup the foreign key
197 * constraints. [#15358]
198 */
199 inverseRelatedEntityMap = new HashMap<String, Set<String>>();
200 List<Format> entityFormats = new ArrayList<Format>();
201 catalog.getEntityFormats(entityFormats);
202 for (Format entityFormat : entityFormats) {
203 EntityMetadata entityMeta = entityFormat.getEntityMetadata();
204 for (SecondaryKeyMetadata secKeyMeta :
205 entityMeta.getSecondaryKeys().values()) {
206 String relatedClsName = secKeyMeta.getRelatedEntity();
207 if (relatedClsName != null) {
208 Set<String> inverseClassNames =
209 inverseRelatedEntityMap.get(relatedClsName);
210 if (inverseClassNames == null) {
211 inverseClassNames = new HashSet<String>();
212 inverseRelatedEntityMap.put
213 (relatedClsName, inverseClassNames);
214 }
215 inverseClassNames.add(entityMeta.getClassName());
216 }
217 }
218 }
219 }
220
221 public Environment getEnvironment() {
222 return env;
223 }
224
225 public StoreConfig getConfig() {
226 return storeConfig.clone();
227 }
228
229 public String getStoreName() {
230 return storeName;
231 }
232
233
234 /**
235 * For unit testing.
236 */
237 public boolean isReplicaUpgradeMode() {
238 return catalog.isReplicaUpgradeMode();
239 }
240
241 public EntityModel getModel() {
242 return model;
243 }
244
245 public Mutations getMutations() {
246 return catalog.getMutations();
247 }
248
249 /**
250 * A getPrimaryIndex with extra parameters for opening a raw store.
251 * primaryKeyClass and entityClass are used for generic typing; for a raw
252 * store, these should always be Object.class and RawObject.class.
253 * primaryKeyClassName is used for consistency checking and should be null
254 * for a raw store only. entityClassName is used to identify the store and
255 * may not be null.
256 */
257 public synchronized <PK, E> PrimaryIndex<PK, E>
258 getPrimaryIndex(Class<PK> primaryKeyClass,
259 String primaryKeyClassName,
260 Class<E> entityClass,
261 String entityClassName)
262 throws DatabaseException, IndexNotAvailableException {
263
264 assert (rawAccess && entityClass == RawObject.class) ||
265 (!rawAccess && entityClass != RawObject.class);
266 assert (rawAccess && primaryKeyClassName == null) ||
267 (!rawAccess && primaryKeyClassName != null);
268
269 checkOpen();
270
271 InternalPrimaryIndex<PK, E> priIndex =
272 priIndexMap.get(entityClassName);
273 if (priIndex == null) {
274
275 /* Check metadata. */
276 EntityMetadata entityMeta = checkEntityClass(entityClassName);
277 PrimaryKeyMetadata priKeyMeta = entityMeta.getPrimaryKey();
278 if (primaryKeyClassName == null) {
279 primaryKeyClassName = priKeyMeta.getClassName();
280 } else {
281 String expectClsName =
282 SimpleCatalog.keyClassName(priKeyMeta.getClassName());
283 if (!primaryKeyClassName.equals(expectClsName)) {
284 throw new IllegalArgumentException
285 ("Wrong primary key class: " + primaryKeyClassName +
286 " Correct class is: " + expectClsName);
287 }
288 }
289
290 /* Create bindings. */
291 PersistEntityBinding entityBinding =
292 new PersistEntityBinding(catalog, entityClassName, rawAccess);
293 PersistKeyBinding keyBinding = getKeyBinding(primaryKeyClassName);
294
295 /* If not read-only, get the primary key sequence. */
296 String seqName = priKeyMeta.getSequenceName();
297 if (!storeConfig.getReadOnly() && seqName != null) {
298 entityBinding.keyAssigner = new PersistKeyAssigner
299 (keyBinding, entityBinding, getSequence(seqName));
300 }
301
302 /*
303 * Use a single transaction for opening the primary DB and its
304 * secondaries. If opening any secondary fails, abort the
305 * transaction and undo the changes to the state of the store.
306 * Also support undo if the store is non-transactional.
307 *
308 * Use a no-wait transaction to avoid blocking on a Replica while
309 * attempting to open an index that is currently being populated
310 * via the replication stream from the Master.
311 */
312 Transaction txn = null;
313 DatabaseConfig dbConfig = getPrimaryConfig(entityMeta);
314 if (dbConfig.getTransactional() &&
315 DbCompat.getThreadTransaction(env) == null) {
316 txn = env.beginTransaction(null, autoCommitNoWaitTxnConfig);
317 }
318 PrimaryOpenState priOpenState =
319 new PrimaryOpenState(entityClassName);
320 final boolean saveAllowCreate = dbConfig.getAllowCreate();
321 boolean success = false;
322 try {
323
324 /*
325 * The AllowCreate setting is false in read-only / Replica
326 * upgrade mode. In this mode new primaries are not available.
327 * They can be opened later when the upgrade is complete on the
328 * Master, by calling getSecondaryIndex. [#16655]
329 */
330 if (catalog.isReadOnly()) {
331 dbConfig.setAllowCreate(false);
332 }
333
334 /*
335 * Open the primary database. Account for database renaming
336 * by calling getDatabaseClassName. The dbClassName will be
337 * null if the format has not yet been stored. [#16655].
338 */
339 Database db = null;
340 final String dbClassName =
341 catalog.getDatabaseClassName(entityClassName);
342 if (dbClassName != null) {
343 final String[] fileAndDbNames =
344 parseDbName(storePrefix + dbClassName);
345 db = DbCompat.openDatabase(env, txn, fileAndDbNames[0],
346 fileAndDbNames[1],
347 dbConfig);
348 }
349 if (db == null) {
350 throw new IndexNotAvailableException
351 ("PrimaryIndex not yet available on this Replica, " +
352 "entity class: " + entityClassName);
353 }
354
355 priOpenState.addDatabase(db);
356
357 /* Create index object. */
358 priIndex = new InternalPrimaryIndex(db, primaryKeyClass,
359 keyBinding, entityClass,
360 entityBinding);
361
362 /* Update index and database maps. */
363 priIndexMap.put(entityClassName, priIndex);
364 if (DbCompat.getDeferredWrite(dbConfig)) {
365 deferredWriteDatabases.put(db, null);
366 }
367
368 /* If not read-only, open all associated secondaries. */
369 if (!dbConfig.getReadOnly()) {
370 openSecondaryIndexes(txn, entityMeta, priOpenState);
371
372 /*
373 * To enable foreign key contraints, also open all primary
374 * indexes referring to this class via a relatedEntity
375 * property in another entity. [#15358]
376 */
377 Set<String> inverseClassNames =
378 inverseRelatedEntityMap.get(entityClassName);
379 if (inverseClassNames != null) {
380 for (String relatedClsName : inverseClassNames) {
381 getRelatedIndex(relatedClsName);
382 }
383 }
384 }
385 success = true;
386 } finally {
387 dbConfig.setAllowCreate(saveAllowCreate);
388 if (success) {
389 if (txn != null) {
390 txn.commit();
391 }
392 } else {
393 if (txn != null) {
394 txn.abort();
395 }
396 priOpenState.undoState();
397 }
398 }
399 }
400 return priIndex;
401 }
402
403 /**
404 * Holds state information about opening a primary index and its secondary
405 * indexes. Used to undo the state of this object if the transaction
406 * opening the primary and secondaries aborts. Also used to close all
407 * databases opened during this process for a non-transactional store.
408 */
409 private class PrimaryOpenState {
410
411 private String entityClassName;
412 private IdentityHashMap<Database, Object> databases;
413 private Set<String> secNames;
414
415 PrimaryOpenState(String entityClassName) {
416 this.entityClassName = entityClassName;
417 databases = new IdentityHashMap<Database, Object>();
418 secNames = new HashSet<String>();
419 }
420
421 /**
422 * Save a database that was opening during this operation.
423 */
424 void addDatabase(Database db) {
425 databases.put(db, null);
426 }
427
428 /**
429 * Save the name of a secondary index that was opening during this
430 * operation.
431 */
432 void addSecondaryName(String secName) {
433 secNames.add(secName);
434 }
435
436 /**
437 * Reset all state information and closes any databases opened, when
438 * this operation fails. This method should be called for both
439 * transactional and non-transsactional operation.
440 *
441 * For transactional operations on JE, we don't strictly need to close
442 * the databases since the transaction abort will do that. However,
443 * closing them is harmless on JE, and required for DB core.
444 */
445 void undoState() {
446 for (Database db : databases.keySet()) {
447 try {
448 db.close();
449 } catch (Exception ignored) {
450 }
451 }
452 priIndexMap.remove(entityClassName);
453 for (String secName : secNames) {
454 secIndexMap.remove(secName);
455 }
456 for (Database db : databases.keySet()) {
457 deferredWriteDatabases.remove(db);
458 }
459 }
460 }
461
462 /**
463 * Opens a primary index related via a foreign key (relatedEntity).
464 * Related indexes are not opened in the same transaction used by the
465 * caller to open a primary or secondary. It is OK to leave the related
466 * index open when the caller's transaction aborts. It is only important
467 * to open a primary and its secondaries atomically.
468 */
469 private PrimaryIndex getRelatedIndex(String relatedClsName)
470 throws DatabaseException {
471
472 PrimaryIndex relatedIndex = priIndexMap.get(relatedClsName);
473 if (relatedIndex == null) {
474 EntityMetadata relatedEntityMeta =
475 checkEntityClass(relatedClsName);
476 Class relatedKeyCls;
477 String relatedKeyClsName;
478 Class relatedCls;
479 if (rawAccess) {
480 relatedCls = RawObject.class;
481 relatedKeyCls = Object.class;
482 relatedKeyClsName = null;
483 } else {
484 try {
485 relatedCls = catalog.resolveClass(relatedClsName);
486 } catch (ClassNotFoundException e) {
487 throw new IllegalArgumentException
488 ("Related entity class not found: " +
489 relatedClsName);
490 }
491 relatedKeyClsName = SimpleCatalog.keyClassName
492 (relatedEntityMeta.getPrimaryKey().getClassName());
493 relatedKeyCls = catalog.resolveKeyClass(relatedKeyClsName);
494 }
495
496 /*
497 * Cycles are prevented here by adding primary indexes to the
498 * priIndexMap as soon as they are created, before opening related
499 * indexes.
500 */
501 relatedIndex = getPrimaryIndex
502 (relatedKeyCls, relatedKeyClsName,
503 relatedCls, relatedClsName);
504 }
505 return relatedIndex;
506 }
507
508 /**
509 * A getSecondaryIndex with extra parameters for opening a raw store.
510 * keyClassName is used for consistency checking and should be null for a
511 * raw store only.
512 */
513 public synchronized <SK, PK, E1, E2 extends E1> SecondaryIndex<SK, PK, E2>
514 getSecondaryIndex(PrimaryIndex<PK, E1> primaryIndex,
515 Class<E2> entityClass,
516 String entityClassName,
517 Class<SK> keyClass,
518 String keyClassName,
519 String keyName)
520 throws DatabaseException, IndexNotAvailableException {
521
522 assert (rawAccess && keyClassName == null) ||
523 (!rawAccess && keyClassName != null);
524
525 checkOpen();
526
527 EntityMetadata entityMeta = null;
528 SecondaryKeyMetadata secKeyMeta = null;
529
530 /* Validate the subclass for a subclass index. */
531 if (entityClass != primaryIndex.getEntityClass()) {
532 entityMeta = model.getEntityMetadata(entityClassName);
533 assert entityMeta != null;
534 secKeyMeta = checkSecKey(entityMeta, keyName);
535 String subclassName = entityClass.getName();
536 String declaringClassName = secKeyMeta.getDeclaringClassName();
537 if (!subclassName.equals(declaringClassName)) {
538 throw new IllegalArgumentException
539 ("Key for subclass " + subclassName +
540 " is declared in a different class: " +
541 makeSecName(declaringClassName, keyName));
542 }
543
544 /*
545 * Get/create the subclass format to ensure it is stored in the
546 * catalog, even if no instances of the subclass are stored.
547 * [#16399]
548 */
549 try {
550 catalog.getFormat(entityClass,
551 false /*checkEntitySubclassIndexes*/);
552 } catch (RefreshException e) {
553 e.refresh();
554 try {
555 catalog.getFormat(entityClass,
556 false /*checkEntitySubclassIndexes*/);
557 } catch (RefreshException e2) {
558 throw DbCompat.unexpectedException(e2);
559 }
560 }
561 }
562
563 /*
564 * Even though the primary is already open, we can't assume the
565 * secondary is open because we don't automatically open all
566 * secondaries when the primary is read-only. Use auto-commit (a null
567 * transaction) since we're opening only one database.
568 */
569 String secName = makeSecName(entityClassName, keyName);
570 InternalSecondaryIndex<SK, PK, E2> secIndex = secIndexMap.get(secName);
571 if (secIndex == null) {
572 if (entityMeta == null) {
573 entityMeta = model.getEntityMetadata(entityClassName);
574 assert entityMeta != null;
575 }
576 if (secKeyMeta == null) {
577 secKeyMeta = checkSecKey(entityMeta, keyName);
578 }
579
580 /* Check metadata. */
581 if (keyClassName == null) {
582 keyClassName = getSecKeyClass(secKeyMeta);
583 } else {
584 String expectClsName = getSecKeyClass(secKeyMeta);
585 if (!keyClassName.equals(expectClsName)) {
586 throw new IllegalArgumentException
587 ("Wrong secondary key class: " + keyClassName +
588 " Correct class is: " + expectClsName);
589 }
590 }
591
592 /*
593 * Account for database renaming. The dbClassName or dbKeyName
594 * will be null if the format has not yet been stored. [#16655]
595 */
596 final String dbClassName =
597 catalog.getDatabaseClassName(entityClassName);
598 final String dbKeyName =
599 catalog.getDatabaseKeyName(entityClassName, keyName);
600 if (dbClassName != null && dbKeyName != null) {
601
602 /*
603 * Use a no-wait transaction to avoid blocking on a Replica
604 * while attempting to open an index that is currently being
605 * populated via the replication stream from the Master.
606 */
607 Transaction txn = null;
608 if (getPrimaryConfig(entityMeta).getTransactional() &&
609 DbCompat.getThreadTransaction(env) == null) {
610 txn = env.beginTransaction(null,
611 autoCommitNoWaitTxnConfig);
612 }
613 boolean success = false;
614 try {
615
616 /*
617 * The doNotCreate param is true below in read-only /
618 * Replica upgrade mode. In this mode new secondaries are
619 * not available. They can be opened later when the
620 * upgrade is complete on the Master, by calling
621 * getSecondaryIndex. [#16655]
622 */
623 secIndex = openSecondaryIndex
624 (txn, primaryIndex, entityClass, entityMeta,
625 keyClass, keyClassName, secKeyMeta, secName,
626 makeSecName(dbClassName, dbKeyName),
627 catalog.isReadOnly() /*doNotCreate*/,
628 null /*priOpenState*/);
629 success = true;
630 } finally {
631 if (success) {
632 if (txn != null) {
633 txn.commit();
634 }
635 } else {
636 if (txn != null) {
637 txn.abort();
638 }
639 }
640 }
641 }
642 if (secIndex == null) {
643 throw new IndexNotAvailableException
644 ("SecondaryIndex not yet available on this Replica, " +
645 "entity class: " + entityClassName + ", key name: " +
646 keyName);
647 }
648 }
649 return secIndex;
650 }
651
652 /**
653 * Opens secondary indexes for a given primary index metadata.
654 */
655 private void openSecondaryIndexes(Transaction txn,
656 EntityMetadata entityMeta,
657 PrimaryOpenState priOpenState)
658 throws DatabaseException {
659
660 String entityClassName = entityMeta.getClassName();
661 PrimaryIndex<Object, Object> priIndex =
662 priIndexMap.get(entityClassName);
663 assert priIndex != null;
664 Class<Object> entityClass = priIndex.getEntityClass();
665
666 for (SecondaryKeyMetadata secKeyMeta :
667 entityMeta.getSecondaryKeys().values()) {
668 String keyName = secKeyMeta.getKeyName();
669 String secName = makeSecName(entityClassName, keyName);
670 SecondaryIndex<Object, Object, Object> secIndex =
671 secIndexMap.get(secName);
672 if (secIndex == null) {
673 String keyClassName = getSecKeyClass(secKeyMeta);
674 /* RawMode: should not require class. */
675 Class keyClass = catalog.resolveKeyClass(keyClassName);
676
677 /*
678 * Account for database renaming. The dbClassName or dbKeyName
679 * will be null if the format has not yet been stored. [#16655]
680 */
681 final String dbClassName =
682 catalog.getDatabaseClassName(entityClassName);
683 final String dbKeyName =
684 catalog.getDatabaseKeyName(entityClassName, keyName);
685 if (dbClassName != null && dbKeyName != null) {
686
687 /*
688 * The doNotCreate param is true below in two cases:
689 * 1- When SecondaryBulkLoad=true, new secondaries are not
690 * created/populated until getSecondaryIndex is called.
691 * 2- In read-only / Replica upgrade mode, new secondaries
692 * are not openeed when the primary is opened. They can
693 * be opened later when the upgrade is complete on the
694 * Master, by calling getSecondaryIndex. [#16655]
695 */
696 openSecondaryIndex
697 (txn, priIndex, entityClass, entityMeta,
698 keyClass, keyClassName, secKeyMeta,
699 secName, makeSecName(dbClassName, dbKeyName),
700 (storeConfig.getSecondaryBulkLoad() ||
701 catalog.isReadOnly()) /*doNotCreate*/,
702 priOpenState);
703 }
704 }
705 }
706 }
707
708 /**
709 * Opens a secondary index with a given transaction and adds it to the
710 * secIndexMap. We assume that the index is not already open.
711 */
712 private <SK, PK, E1, E2 extends E1> InternalSecondaryIndex<SK, PK, E2>
713 openSecondaryIndex(Transaction txn,
714 PrimaryIndex<PK, E1> primaryIndex,
715 Class<E2> entityClass,
716 EntityMetadata entityMeta,
717 Class<SK> keyClass,
718 String keyClassName,
719 SecondaryKeyMetadata secKeyMeta,
720 String secName,
721 String dbSecName,
722 boolean doNotCreate,
723 PrimaryOpenState priOpenState)
724 throws DatabaseException {
725
726 assert !secIndexMap.containsKey(secName);
727 String[] fileAndDbNames = parseDbName(storePrefix + dbSecName);
728 SecondaryConfig config =
729 getSecondaryConfig(secName, entityMeta, keyClassName, secKeyMeta);
730 Database priDb = primaryIndex.getDatabase();
731 DatabaseConfig priConfig = priDb.getConfig();
732
733 String relatedClsName = secKeyMeta.getRelatedEntity();
734 if (relatedClsName != null) {
735 PrimaryIndex relatedIndex = getRelatedIndex(relatedClsName);
736 config.setForeignKeyDatabase(relatedIndex.getDatabase());
737 }
738
739 if (config.getTransactional() != priConfig.getTransactional() ||
740 DbCompat.getDeferredWrite(config) !=
741 DbCompat.getDeferredWrite(priConfig) ||
742 config.getReadOnly() != priConfig.getReadOnly()) {
743 throw new IllegalArgumentException
744 ("One of these properties was changed to be inconsistent" +
745 " with the associated primary database: " +
746 " Transactional, DeferredWrite, ReadOnly");
747 }
748
749 PersistKeyBinding keyBinding = getKeyBinding(keyClassName);
750
751 SecondaryDatabase db = openSecondaryDatabase
752 (txn, fileAndDbNames, primaryIndex,
753 secKeyMeta.getKeyName(), config, doNotCreate);
754 if (db == null) {
755 assert doNotCreate;
756 return null;
757 }
758
759 InternalSecondaryIndex<SK, PK, E2> secIndex =
760 new InternalSecondaryIndex(db, primaryIndex, keyClass, keyBinding,
761 getKeyCreator(config));
762
763 /* Update index and database maps. */
764 secIndexMap.put(secName, secIndex);
765 if (DbCompat.getDeferredWrite(config)) {
766 deferredWriteDatabases.put(db, null);
767 }
768 if (priOpenState != null) {
769 priOpenState.addDatabase(db);
770 priOpenState.addSecondaryName(secName);
771 }
772 return secIndex;
773 }
774
775 /**
776 * Open a secondary database, setting AllowCreate, ExclusiveCreate and
777 * AllowPopulate appropriately. We either set all three of these params to
778 * true or all to false. This ensures that we only populate a database
779 * when it is created, never if it just happens to be empty. [#16399]
780 *
781 * We also handle correction of a bug in duplicate ordering. See
782 * ComplexFormat.incorrectlyOrderedSecKeys.
783 *
784 * @param doNotCreate is true when StoreConfig.getSecondaryBulkLoad is true
785 * and we are opening a secondary as a side effect of opening a primary,
786 * i.e., getSecondaryIndex is not being called. If doNotCreate is true and
787 * the database does not exist, we silently ignore the failure to create
788 * the DB and return null. When getSecondaryIndex is subsequently called,
789 * the secondary database will be created and populated from the primary --
790 * a bulk load.
791 */
792 private SecondaryDatabase
793 openSecondaryDatabase(final Transaction txn,
794 final String[] fileAndDbNames,
795 final PrimaryIndex priIndex,
796 final String keyName,
797 final SecondaryConfig config,
798 final boolean doNotCreate)
799 throws DatabaseException {
800
801 assert config.getAllowPopulate();
802 assert !config.getExclusiveCreate();
803 final Database priDb = priIndex.getDatabase();
804 final ComplexFormat entityFormat = (ComplexFormat)
805 ((PersistEntityBinding) priIndex.getEntityBinding()).entityFormat;
806 final boolean saveAllowCreate = config.getAllowCreate();
807 final Comparator<byte[]> saveDupComparator =
808 config.getDuplicateComparator();
809 try {
810 if (doNotCreate) {
811 config.setAllowCreate(false);
812 }
813 /* First try creating a new database, populate if needed. */
814 if (config.getAllowCreate()) {
815 config.setExclusiveCreate(true);
816 /* AllowPopulate is true; comparators are set. */
817 final SecondaryDatabase db = DbCompat.openSecondaryDatabase
818 (env, txn, fileAndDbNames[0], fileAndDbNames[1], priDb,
819 config);
820 if (db != null) {
821 /* For unit testing. */
822 boolean doFlush = false;
823 /* Update dup ordering bug info. [#17252] */
824 if (config.getDuplicateComparator() != null &&
825 entityFormat.setSecKeyCorrectlyOrdered(keyName)) {
826 catalog.flush(txn);
827 doFlush = true;
828 }
829
830 /*
831 * expectFlush is false except when set by
832 * SecondaryDupOrderTest.
833 */
834 assert !expectFlush || doFlush;
835
836 return db;
837 }
838 }
839 /* Next try opening an existing database. */
840 config.setAllowCreate(false);
841 config.setAllowPopulate(false);
842 config.setExclusiveCreate(false);
843
844 /* Account for dup ordering bug. [#17252] */
845 if (config.getDuplicateComparator() != null &&
846 entityFormat.isSecKeyIncorrectlyOrdered(keyName)) {
847 config.setDuplicateComparator((Comparator<byte[]>) null);
848 }
849 final SecondaryDatabase db = DbCompat.openSecondaryDatabase
850 (env, txn, fileAndDbNames[0], fileAndDbNames[1], priDb,
851 config);
852 return db;
853 } finally {
854 config.setAllowPopulate(true);
855 config.setExclusiveCreate(false);
856 config.setAllowCreate(saveAllowCreate);
857 config.setDuplicateComparator(saveDupComparator);
858 }
859 }
860
861 /**
862 * Checks that all secondary indexes defined in the given entity metadata
863 * are already open. This method is called when a new entity subclass
864 * is encountered when an instance of that class is stored. [#16399]
865 *
866 * @throws IllegalArgumentException if a secondary is not open.
867 */
868 synchronized void
869 checkEntitySubclassSecondaries(final EntityMetadata entityMeta,
870 final String subclassName)
871 throws DatabaseException {
872
873 if (storeConfig.getSecondaryBulkLoad()) {
874 return;
875 }
876
877 final String entityClassName = entityMeta.getClassName();
878
879 for (final SecondaryKeyMetadata secKeyMeta :
880 entityMeta.getSecondaryKeys().values()) {
881 final String keyName = secKeyMeta.getKeyName();
882 final String secName = makeSecName(entityClassName, keyName);
883 if (!secIndexMap.containsKey(secName)) {
884 throw new IllegalArgumentException
885 ("Entity subclasses defining a secondary key must be " +
886 "registered by calling EntityModel.registerClass or " +
887 "EntityStore.getSubclassIndex before storing an " +
888 "instance of the subclass: " + subclassName);
889 }
890 }
891 }
892
893
894 public void truncateClass(Class entityClass)
895 throws DatabaseException {
896
897 truncateClass(null, entityClass);
898 }
899
900 public synchronized void truncateClass(Transaction txn, Class entityClass)
901 throws DatabaseException {
902
903 checkOpen();
904 checkWriteAllowed();
905
906 /* Close primary and secondary databases. */
907 closeClass(entityClass);
908
909 String clsName = entityClass.getName();
910 EntityMetadata entityMeta = checkEntityClass(clsName);
911
912 boolean autoCommit = false;
913 if (storeConfig.getTransactional() &&
914 txn == null &&
915 DbCompat.getThreadTransaction(env) == null) {
916 txn = env.beginTransaction(null, autoCommitTxnConfig);
917 autoCommit = true;
918 }
919
920 /*
921 * Truncate the primary first and let any exceptions propogate
922 * upwards. Then remove each secondary, only throwing the first
923 * exception.
924 */
925 boolean success = false;
926 try {
927 boolean primaryExists =
928 truncateIfExists(txn, storePrefix + clsName);
929 if (primaryExists) {
930 DatabaseException firstException = null;
931 for (SecondaryKeyMetadata keyMeta :
932 entityMeta.getSecondaryKeys().values()) {
933 /* Ignore secondaries that do not exist. */
934 removeIfExists
935 (txn,
936 storePrefix +
937 makeSecName(clsName, keyMeta.getKeyName()));
938 }
939 if (firstException != null) {
940 throw firstException;
941 }
942 }
943 success = true;
944 } finally {
945 if (autoCommit) {
946 if (success) {
947 txn.commit();
948 } else {
949 txn.abort();
950 }
951 }
952 }
953 }
954
955 private boolean truncateIfExists(Transaction txn, String dbName)
956 throws DatabaseException {
957
958 String[] fileAndDbNames = parseDbName(dbName);
959 return DbCompat.truncateDatabase
960 (env, txn, fileAndDbNames[0], fileAndDbNames[1]);
961 }
962
963 private boolean removeIfExists(Transaction txn, String dbName)
964 throws DatabaseException {
965
966 String[] fileAndDbNames = parseDbName(dbName);
967 return DbCompat.removeDatabase
968 (env, txn, fileAndDbNames[0], fileAndDbNames[1]);
969 }
970
971 public synchronized void closeClass(Class entityClass)
972 throws DatabaseException {
973
974 checkOpen();
975 String clsName = entityClass.getName();
976 EntityMetadata entityMeta = checkEntityClass(clsName);
977
978 PrimaryIndex priIndex = priIndexMap.get(clsName);
979 if (priIndex != null) {
980 /* Close the secondaries first. */
981 DatabaseException firstException = null;
982 for (SecondaryKeyMetadata keyMeta :
983 entityMeta.getSecondaryKeys().values()) {
984
985 String secName = makeSecName(clsName, keyMeta.getKeyName());
986 SecondaryIndex secIndex = secIndexMap.get(secName);
987 if (secIndex != null) {
988 Database db = secIndex.getDatabase();
989 firstException = closeDb(db, firstException);
990 firstException =
991 closeDb(secIndex.getKeysDatabase(), firstException);
992 secIndexMap.remove(secName);
993 deferredWriteDatabases.remove(db);
994 }
995 }
996 /* Close the primary last. */
997 Database db = priIndex.getDatabase();
998 firstException = closeDb(db, firstException);
999 priIndexMap.remove(clsName);
1000 deferredWriteDatabases.remove(db);
1001
1002 /* Throw the first exception encountered. */
1003 if (firstException != null) {
1004 throw firstException;
1005 }
1006 }
1007 }
1008
1009 public synchronized void close()
1010 throws DatabaseException {
1011
1012 if (catalog == null) {
1013 return;
1014 }
1015
1016 DatabaseException firstException = null;
1017 try {
1018 if (rawAccess) {
1019 boolean allClosed = catalog.close();
1020 assert allClosed;
1021 } else {
1022 synchronized (catalogPool) {
1023 Map<String, PersistCatalog> catalogMap =
1024 catalogPool.get(env);
1025 assert catalogMap != null;
1026 if (catalog.close()) {
1027 /* Remove when the reference count goes to zero. */
1028 catalogMap.remove(storeName);
1029 }
1030 }
1031 }
1032 catalog = null;
1033 } catch (DatabaseException e) {
1034 if (firstException == null) {
1035 firstException = e;
1036 }
1037 }
1038 for (Sequence seq : sequenceMap.values()) {
1039 try {
1040 seq.close();
1041 } catch (DatabaseException e) {
1042 if (firstException == null) {
1043 firstException = e;
1044 }
1045 }
1046 }
1047 firstException = closeDb(sequenceDb, firstException);
1048 for (SecondaryIndex index : secIndexMap.values()) {
1049 firstException = closeDb(index.getDatabase(), firstException);
1050 firstException = closeDb(index.getKeysDatabase(), firstException);
1051 }
1052 for (PrimaryIndex index : priIndexMap.values()) {
1053 firstException = closeDb(index.getDatabase(), firstException);
1054 }
1055 if (firstException != null) {
1056 throw firstException;
1057 }
1058 }
1059
1060 public synchronized Sequence getSequence(String name)
1061 throws DatabaseException {
1062
1063 checkOpen();
1064
1065 if (storeConfig.getReadOnly()) {
1066 throw new IllegalStateException("Store is read-only");
1067 }
1068
1069 Sequence seq = sequenceMap.get(name);
1070 if (seq == null) {
1071 if (sequenceDb == null) {
1072 String[] fileAndDbNames =
1073 parseDbName(storePrefix + SEQUENCE_DB);
1074 DatabaseConfig dbConfig = new DatabaseConfig();
1075 dbConfig.setTransactional(storeConfig.getTransactional());
1076 dbConfig.setAllowCreate(true);
1077 DbCompat.setTypeBtree(dbConfig);
1078 sequenceDb = DbCompat.openDatabase
1079 (env, null /*txn*/, fileAndDbNames[0], fileAndDbNames[1],
1080 dbConfig);
1081 assert sequenceDb != null;
1082 }
1083
1084 DatabaseEntry entry = new DatabaseEntry();
1085 StringBinding.stringToEntry(name, entry);
1086 seq = sequenceDb.openSequence(null /*txn*/, entry,
1087 getSequenceConfig(name));
1088 sequenceMap.put(name, seq);
1089 }
1090 return seq;
1091 }
1092
1093 public synchronized SequenceConfig getSequenceConfig(String name) {
1094 checkOpen();
1095 SequenceConfig config = sequenceConfigMap.get(name);
1096 if (config == null) {
1097 config = new SequenceConfig();
1098 config.setInitialValue(1);
1099 config.setRange(1, Long.MAX_VALUE);
1100 config.setCacheSize(100);
1101 config.setAutoCommitNoSync(true);
1102 config.setAllowCreate(!storeConfig.getReadOnly());
1103 sequenceConfigMap.put(name, config);
1104 }
1105 return config;
1106 }
1107
1108 public synchronized void setSequenceConfig(String name,
1109 SequenceConfig config) {
1110 checkOpen();
1111 if (config.getExclusiveCreate() ||
1112 config.getAllowCreate() == storeConfig.getReadOnly()) {
1113 throw new IllegalArgumentException
1114 ("One of these properties was illegally changed: " +
1115 "AllowCreate, ExclusiveCreate");
1116 }
1117 if (sequenceMap.containsKey(name)) {
1118 throw new IllegalStateException
1119 ("Cannot set config after Sequence is open");
1120 }
1121 sequenceConfigMap.put(name, config);
1122 }
1123
1124 public synchronized DatabaseConfig getPrimaryConfig(Class entityClass) {
1125 checkOpen();
1126 String clsName = entityClass.getName();
1127 EntityMetadata meta = checkEntityClass(clsName);
1128 return getPrimaryConfig(meta).cloneConfig();
1129 }
1130
1131 private synchronized DatabaseConfig getPrimaryConfig(EntityMetadata meta) {
1132 String clsName = meta.getClassName();
1133 DatabaseConfig config = priConfigMap.get(clsName);
1134 if (config == null) {
1135 config = new DatabaseConfig();
1136 config.setTransactional(storeConfig.getTransactional());
1137 config.setAllowCreate(!storeConfig.getReadOnly());
1138 config.setReadOnly(storeConfig.getReadOnly());
1139 DbCompat.setTypeBtree(config);
1140 setBtreeComparator(config, meta.getPrimaryKey().getClassName());
1141 priConfigMap.put(clsName, config);
1142 }
1143 return config;
1144 }
1145
1146 public synchronized void setPrimaryConfig(Class entityClass,
1147 DatabaseConfig config) {
1148 checkOpen();
1149 String clsName = entityClass.getName();
1150 if (priIndexMap.containsKey(clsName)) {
1151 throw new IllegalStateException
1152 ("Cannot set config after DB is open");
1153 }
1154 EntityMetadata meta = checkEntityClass(clsName);
1155 DatabaseConfig dbConfig = getPrimaryConfig(meta);
1156 if (config.getExclusiveCreate() ||
1157 config.getAllowCreate() == config.getReadOnly() ||
1158 config.getSortedDuplicates() ||
1159 config.getBtreeComparator() != dbConfig.getBtreeComparator()) {
1160 throw new IllegalArgumentException
1161 ("One of these properties was illegally changed: " +
1162 "AllowCreate, ExclusiveCreate, SortedDuplicates, Temporary " +
1163 "or BtreeComparator, ");
1164 }
1165 if (!DbCompat.isTypeBtree(config)) {
1166 throw new IllegalArgumentException("Only type BTREE allowed");
1167 }
1168 priConfigMap.put(clsName, config);
1169 }
1170
1171 public synchronized SecondaryConfig getSecondaryConfig(Class entityClass,
1172 String keyName) {
1173 checkOpen();
1174 String entityClsName = entityClass.getName();
1175 EntityMetadata entityMeta = checkEntityClass(entityClsName);
1176 SecondaryKeyMetadata secKeyMeta = checkSecKey(entityMeta, keyName);
1177 String keyClassName = getSecKeyClass(secKeyMeta);
1178 String secName = makeSecName(entityClass.getName(), keyName);
1179 return (SecondaryConfig) getSecondaryConfig
1180 (secName, entityMeta, keyClassName, secKeyMeta).cloneConfig();
1181 }
1182
1183 private SecondaryConfig getSecondaryConfig(String secName,
1184 EntityMetadata entityMeta,
1185 String keyClassName,
1186 SecondaryKeyMetadata
1187 secKeyMeta) {
1188 SecondaryConfig config = secConfigMap.get(secName);
1189 if (config == null) {
1190 /* Set common properties to match the primary DB. */
1191 DatabaseConfig priConfig = getPrimaryConfig(entityMeta);
1192 config = new SecondaryConfig();
1193 config.setTransactional(priConfig.getTransactional());
1194 config.setAllowCreate(!priConfig.getReadOnly());
1195 config.setReadOnly(priConfig.getReadOnly());
1196 DbCompat.setTypeBtree(config);
1197 /* Set secondary properties based on metadata. */
1198 config.setAllowPopulate(true);
1199 Relationship rel = secKeyMeta.getRelationship();
1200 config.setSortedDuplicates(rel == Relationship.MANY_TO_ONE ||
1201 rel == Relationship.MANY_TO_MANY);
1202 setBtreeComparator(config, keyClassName);
1203 config.setDuplicateComparator(priConfig.getBtreeComparator());
1204 PersistKeyCreator keyCreator = new PersistKeyCreator
1205 (catalog, entityMeta, keyClassName, secKeyMeta, rawAccess);
1206 if (rel == Relationship.ONE_TO_MANY ||
1207 rel == Relationship.MANY_TO_MANY) {
1208 config.setMultiKeyCreator(keyCreator);
1209 } else {
1210 config.setKeyCreator(keyCreator);
1211 }
1212 DeleteAction deleteAction = secKeyMeta.getDeleteAction();
1213 if (deleteAction != null) {
1214 ForeignKeyDeleteAction baseDeleteAction;
1215 switch (deleteAction) {
1216 case ABORT:
1217 baseDeleteAction = ForeignKeyDeleteAction.ABORT;
1218 break;
1219 case CASCADE:
1220 baseDeleteAction = ForeignKeyDeleteAction.CASCADE;
1221 break;
1222 case NULLIFY:
1223 baseDeleteAction = ForeignKeyDeleteAction.NULLIFY;
1224 break;
1225 default:
1226 throw DbCompat.unexpectedState(deleteAction.toString());
1227 }
1228 config.setForeignKeyDeleteAction(baseDeleteAction);
1229 if (deleteAction == DeleteAction.NULLIFY) {
1230 config.setForeignMultiKeyNullifier(keyCreator);
1231 }
1232 }
1233 secConfigMap.put(secName, config);
1234 }
1235 return config;
1236 }
1237
1238 public synchronized void setSecondaryConfig(Class entityClass,
1239 String keyName,
1240 SecondaryConfig config) {
1241 checkOpen();
1242 String entityClsName = entityClass.getName();
1243 EntityMetadata entityMeta = checkEntityClass(entityClsName);
1244 SecondaryKeyMetadata secKeyMeta = checkSecKey(entityMeta, keyName);
1245 String keyClassName = getSecKeyClass(secKeyMeta);
1246 String secName = makeSecName(entityClass.getName(), keyName);
1247 if (secIndexMap.containsKey(secName)) {
1248 throw new IllegalStateException
1249 ("Cannot set config after DB is open");
1250 }
1251 SecondaryConfig dbConfig =
1252 getSecondaryConfig(secName, entityMeta, keyClassName, secKeyMeta);
1253 if (config.getExclusiveCreate() ||
1254 config.getAllowCreate() == config.getReadOnly() ||
1255 config.getSortedDuplicates() != dbConfig.getSortedDuplicates() ||
1256 config.getBtreeComparator() != dbConfig.getBtreeComparator() ||
1257 config.getDuplicateComparator() != null ||
1258 config.getAllowPopulate() != dbConfig.getAllowPopulate() ||
1259 config.getKeyCreator() != dbConfig.getKeyCreator() ||
1260 config.getMultiKeyCreator() != dbConfig.getMultiKeyCreator() ||
1261 config.getForeignKeyNullifier() !=
1262 dbConfig.getForeignKeyNullifier() ||
1263 config.getForeignMultiKeyNullifier() !=
1264 dbConfig.getForeignMultiKeyNullifier() ||
1265 config.getForeignKeyDeleteAction() !=
1266 dbConfig.getForeignKeyDeleteAction() ||
1267 config.getForeignKeyDatabase() != null) {
1268 throw new IllegalArgumentException
1269 ("One of these properties was illegally changed: " +
1270 " AllowCreate, ExclusiveCreate, SortedDuplicates," +
1271 " BtreeComparator, DuplicateComparator, Temporary," +
1272 " AllowPopulate, KeyCreator, MultiKeyCreator," +
1273 " ForeignKeyNullifer, ForeignMultiKeyNullifier," +
1274 " ForeignKeyDeleteAction, ForeignKeyDatabase");
1275 }
1276 if (!DbCompat.isTypeBtree(config)) {
1277 throw new IllegalArgumentException("Only type BTREE allowed");
1278 }
1279 secConfigMap.put(secName, config);
1280 }
1281
1282 private static String makeSecName(String entityClsName, String keyName) {
1283 return entityClsName + NAME_SEPARATOR + keyName;
1284 }
1285
1286 static String makePriDbName(String storePrefix, String entityClsName) {
1287 return storePrefix + entityClsName;
1288 }
1289
1290 static String makeSecDbName(String storePrefix,
1291 String entityClsName,
1292 String keyName) {
1293 return storePrefix + makeSecName(entityClsName, keyName);
1294 }
1295
1296 /**
1297 * Parses a whole DB name and returns an array of 2 strings where element 0
1298 * is the file name (always null for JE, always non-null for DB core) and
1299 * element 1 is the logical DB name (always non-null for JE, may be null
1300 * for DB core).
1301 */
1302 public String[] parseDbName(String wholeName) {
1303 return parseDbName(wholeName, storeConfig.getDatabaseNamer());
1304 }
1305
1306 /**
1307 * Allows passing a namer to a static method for testing.
1308 */
1309 public static String[] parseDbName(String wholeName, DatabaseNamer namer) {
1310 String[] result = new String[2];
1311 if (DbCompat.SEPARATE_DATABASE_FILES) {
1312 String[] splitName = wholeName.split(NAME_SEPARATOR);
1313 assert splitName.length == 3 || splitName.length == 4 : wholeName;
1314 assert splitName[0].equals("persist") : wholeName;
1315 String storeName = splitName[1];
1316 String clsName = splitName[2];
1317 String keyName = (splitName.length > 3) ? splitName[3] : null;
1318 result[0] = namer.getFileName(storeName, clsName, keyName);
1319 result[1] = null;
1320 } else {
1321 result[0] = null;
1322 result[1] = wholeName;
1323 }
1324 return result;
1325 }
1326
1327 /**
1328 * Creates a message identifying the database from the pair of strings
1329 * returned by parseDbName.
1330 */
1331 String getDbNameMessage(String[] names) {
1332 if (DbCompat.SEPARATE_DATABASE_FILES) {
1333 return "file: " + names[0];
1334 } else {
1335 return "database: " + names[1];
1336 }
1337 }
1338
1339 private void checkOpen() {
1340 if (catalog == null) {
1341 throw new IllegalStateException("Store has been closed");
1342 }
1343 }
1344
1345 private void checkWriteAllowed() {
1346 if (catalog.isReadOnly()) {
1347 throw new IllegalStateException
1348 ("Store is read-only or is operating as a Replica");
1349 }
1350 }
1351
1352 private EntityMetadata checkEntityClass(String clsName) {
1353 EntityMetadata meta = model.getEntityMetadata(clsName);
1354 if (meta == null) {
1355 throw new IllegalArgumentException
1356 ("Class could not be loaded or is not an entity class: " +
1357 clsName);
1358 }
1359 return meta;
1360 }
1361
1362 private SecondaryKeyMetadata checkSecKey(EntityMetadata entityMeta,
1363 String keyName) {
1364 SecondaryKeyMetadata secKeyMeta =
1365 entityMeta.getSecondaryKeys().get(keyName);
1366 if (secKeyMeta == null) {
1367 throw new IllegalArgumentException
1368 ("Not a secondary key: " +
1369 makeSecName(entityMeta.getClassName(), keyName));
1370 }
1371 return secKeyMeta;
1372 }
1373
1374 private String getSecKeyClass(SecondaryKeyMetadata secKeyMeta) {
1375 String clsName = secKeyMeta.getElementClassName();
1376 if (clsName == null) {
1377 clsName = secKeyMeta.getClassName();
1378 }
1379 return SimpleCatalog.keyClassName(clsName);
1380 }
1381
1382 private PersistKeyBinding getKeyBinding(String keyClassName) {
1383 PersistKeyBinding binding = keyBindingMap.get(keyClassName);
1384 if (binding == null) {
1385 binding = new PersistKeyBinding(catalog, keyClassName, rawAccess);
1386 keyBindingMap.put(keyClassName, binding);
1387 }
1388 return binding;
1389 }
1390
1391 private PersistKeyCreator getKeyCreator(final SecondaryConfig config) {
1392 PersistKeyCreator keyCreator =
1393 (PersistKeyCreator) config.getKeyCreator();
1394 if (keyCreator != null) {
1395 return keyCreator;
1396 }
1397 keyCreator = (PersistKeyCreator) config.getMultiKeyCreator();
1398 assert keyCreator != null;
1399 return keyCreator;
1400 }
1401
1402 private void setBtreeComparator(DatabaseConfig config, String clsName) {
1403 if (!rawAccess) {
1404 PersistKeyBinding binding = getKeyBinding(clsName);
1405 Format format = binding.keyFormat;
1406 if (format instanceof CompositeKeyFormat) {
1407 Class keyClass = format.getType();
1408 if (Comparable.class.isAssignableFrom(keyClass)) {
1409 config.setBtreeComparator(new PersistComparator(binding));
1410 }
1411 }
1412 }
1413 }
1414
1415 private DatabaseException closeDb(Database db,
1416 DatabaseException firstException) {
1417 if (db != null) {
1418 try {
1419 db.close();
1420 } catch (DatabaseException e) {
1421 if (firstException == null) {
1422 firstException = e;
1423 }
1424 }
1425 }
1426 return firstException;
1427 }
1428
1429 public EvolveStats evolve(EvolveConfig config)
1430 throws DatabaseException {
1431
1432 checkOpen();
1433 checkWriteAllowed();
1434
1435 /*
1436 * Before starting, ensure that we are not in Replica Upgrade Mode and
1437 * the catalog metadata is not stale. If this node is a Replica, a
1438 * ReplicaWriteException will occur further below.
1439 */
1440 if (catalog.isReplicaUpgradeMode() || catalog.isMetadataStale(null)) {
1441 attemptRefresh();
1442 }
1443
1444 /* To ensure consistency use a single catalog instance. [#16655] */
1445 final PersistCatalog useCatalog = catalog;
1446 List<Format> toEvolve = new ArrayList<Format>();
1447 Set<String> configToEvolve = config.getClassesToEvolve();
1448 if (configToEvolve.isEmpty()) {
1449 useCatalog.getEntityFormats(toEvolve);
1450 } else {
1451 for (String name : configToEvolve) {
1452 Format format = useCatalog.getFormat(name);
1453 if (format == null) {
1454 throw new IllegalArgumentException
1455 ("Class to evolve is not persistent: " + name);
1456 }
1457 if (!format.isEntity()) {
1458 throw new IllegalArgumentException
1459 ("Class to evolve is not an entity class: " + name);
1460 }
1461 toEvolve.add(format);
1462 }
1463 }
1464
1465 EvolveEvent event = EvolveInternal.newEvent();
1466 for (Format format : toEvolve) {
1467 if (format.getEvolveNeeded()) {
1468 evolveIndex(format, event, config.getEvolveListener());
1469 format.setEvolveNeeded(false);
1470 useCatalog.flush(null);
1471 }
1472 }
1473
1474 return event.getStats();
1475 }
1476
1477 private void evolveIndex(Format format,
1478 EvolveEvent event,
1479 EvolveListener listener)
1480 throws DatabaseException {
1481
1482 /* We may make this configurable later. */
1483 final int WRITES_PER_TXN = 1;
1484
1485 Class entityClass = format.getType();
1486 String entityClassName = format.getClassName();
1487 EntityMetadata meta = model.getEntityMetadata(entityClassName);
1488 String keyClassName = meta.getPrimaryKey().getClassName();
1489 keyClassName = SimpleCatalog.keyClassName(keyClassName);
1490 DatabaseConfig dbConfig = getPrimaryConfig(meta);
1491
1492 PrimaryIndex<Object, Object> index = getPrimaryIndex
1493 (Object.class, keyClassName, entityClass, entityClassName);
1494 Database db = index.getDatabase();
1495
1496 EntityBinding binding = index.getEntityBinding();
1497 DatabaseEntry key = new DatabaseEntry();
1498 DatabaseEntry data = new DatabaseEntry();
1499
1500 CursorConfig cursorConfig = null;
1501 Transaction txn = null;
1502 if (dbConfig.getTransactional()) {
1503 txn = env.beginTransaction(null, autoCommitTxnConfig);
1504 cursorConfig = CursorConfig.READ_COMMITTED;
1505 }
1506
1507 Cursor cursor = null;
1508 int nWritten = 0;
1509 try {
1510 cursor = db.openCursor(txn, cursorConfig);
1511 OperationStatus status = cursor.getFirst(key, data, null);
1512 while (status == OperationStatus.SUCCESS) {
1513 boolean oneWritten = false;
1514 if (evolveNeeded(key, data, binding)) {
1515 cursor.putCurrent(data);
1516 oneWritten = true;
1517 nWritten += 1;
1518 }
1519 /* Update event stats, even if no listener. [#17024] */
1520 EvolveInternal.updateEvent
1521 (event, entityClassName, 1, oneWritten ? 1 : 0);
1522 if (listener != null) {
1523 if (!listener.evolveProgress(event)) {
1524 break;
1525 }
1526 }
1527 if (txn != null && nWritten >= WRITES_PER_TXN) {
1528 cursor.close();
1529 cursor = null;
1530 txn.commit();
1531 txn = null;
1532 txn = env.beginTransaction(null, autoCommitTxnConfig);
1533 cursor = db.openCursor(txn, cursorConfig);
1534 DatabaseEntry saveKey = KeyRange.copy(key);
1535 status = cursor.getSearchKeyRange(key, data, null);
1536 if (status == OperationStatus.SUCCESS &&
1537 KeyRange.equalBytes(key, saveKey)) {
1538 status = cursor.getNext(key, data, null);
1539 }
1540 } else {
1541 status = cursor.getNext(key, data, null);
1542 }
1543 }
1544 } finally {
1545 if (cursor != null) {
1546 cursor.close();
1547 }
1548 if (txn != null) {
1549 if (nWritten > 0) {
1550 txn.commit();
1551 } else {
1552 txn.abort();
1553 }
1554 }
1555 }
1556 }
1557
1558 /**
1559 * Checks whether the given data is in the current format by translating it
1560 * to/from an object. If true is returned, data is updated.
1561 */
1562 private boolean evolveNeeded(DatabaseEntry key,
1563 DatabaseEntry data,
1564 EntityBinding binding) {
1565 Object entity = binding.entryToObject(key, data);
1566 DatabaseEntry newData = new DatabaseEntry();
1567 binding.objectToData(entity, newData);
1568 if (data.equals(newData)) {
1569 return false;
1570 } else {
1571 byte[] bytes = newData.getData();
1572 int off = newData.getOffset();
1573 int size = newData.getSize();
1574 data.setData(bytes, off, size);
1575 return true;
1576 }
1577 }
1578
1579 /**
1580 * For unit testing.
1581 */
1582 public static void setSyncHook(SyncHook hook) {
1583 syncHook = hook;
1584 }
1585
1586 /**
1587 * For unit testing.
1588 */
1589 public interface SyncHook {
1590 void onSync(Database db);
1591 }
1592
1593 /**
1594 * Attempts to refresh metadata and returns whether a refresh occurred.
1595 * May be called when we expect that updated metadata may be available on
1596 * disk, and if so could be used to satisfy the user's request. For
1597 * example, if an index is requested and not available, we can try a
1598 * refresh and the check for the index again.
1599 */
1600 public boolean attemptRefresh() {
1601 final PersistCatalog oldCatalog = catalog;
1602 final PersistCatalog newCatalog =
1603 refresh(oldCatalog, -1 /*errorFormatId*/, null /*cause*/);
1604 return oldCatalog != newCatalog;
1605 }
1606
1607 /**
1608 * Called via RefreshException.refresh when handling the RefreshException
1609 * in the binding methods, when a Replica detects that its in-memory
1610 * metadata is stale.
1611 *
1612 * During refresh, objects that are visible to the user must not be
1613 * re-created, since the user may have a reference to them. The
1614 * PersistCatalog is re-created by this method, and the additional objects
1615 * listed below are refreshed without creating a new instance. The
1616 * refresh() method of non-indented classes is called, and these methods
1617 * forward the call to indented classes.
1618 *
1619 * PersistCatalog
1620 * EntityModel
1621 * PrimaryIndex
1622 * PersistEntityBinding
1623 * PersistKeyAssigner
1624 * SecondaryIndex
1625 * PersistKeyCreator
1626 * PersistKeyBinding
1627 *
1628 * These objects have volatile catalog and format fields. When a refresh
1629 * in one thread changes these fields, other threads should notice the
1630 * changes ASAP. However, it is not necessary that all access to these
1631 * fields is synchronized. It is Ok for a mix of old and new fields to be
1632 * used at any point in time. If an old object is used after a refresh,
1633 * the need for a refresh may be detected, causing another call to this
1634 * method. In most cases the redundant refresh will be avoided (see check
1635 * below), but in some cases an extra unnecessary refresh may be performed.
1636 * This is undesirable, but is not dangerous. Synchronization must be
1637 * avoided to prevent blocking during read/write operations.
1638 *
1639 * [#16655]
1640 */
1641 synchronized PersistCatalog refresh(final PersistCatalog oldCatalog,
1642 final int errorFormatId,
1643 final RefreshException cause) {
1644
1645 /*
1646 * While synchronized, check to see whether metadata has already been
1647 * refreshed.
1648 */
1649 if (oldCatalog != catalog) {
1650 /* Another thread refreshed the metadata -- nothing to do. */
1651 return catalog;
1652 }
1653
1654 /*
1655 * First refresh the catalog information, then check that the new
1656 * metadata contains the format ID we're interested in using.
1657 */
1658 try {
1659 catalog = new PersistCatalog(oldCatalog, storePrefix);
1660 } catch (DatabaseException e) {
1661 throw RuntimeExceptionWrapper.wrapIfNeeded(e);
1662 }
1663
1664 if (errorFormatId >= catalog.getNFormats()) {
1665 /* Even with current metadata, the format is out of range. */
1666 throw DbCompat.unexpectedException
1667 ("Catalog could not be refreshed, may indicate corruption, " +
1668 "errorFormatId=" + errorFormatId + " nFormats=" +
1669 catalog.getNFormats() + ", .", cause);
1670 }
1671
1672 /*
1673 * Finally refresh all other objects that directly reference catalog
1674 * and format objects.
1675 */
1676 for (InternalPrimaryIndex index : priIndexMap.values()) {
1677 index.refresh(catalog);
1678 }
1679 for (InternalSecondaryIndex index : secIndexMap.values()) {
1680 index.refresh(catalog);
1681 }
1682 for (PersistKeyBinding binding : keyBindingMap.values()) {
1683 binding.refresh(catalog);
1684 }
1685 for (SecondaryConfig config : secConfigMap.values()) {
1686 PersistKeyCreator keyCreator = getKeyCreator(config);
1687 keyCreator.refresh(catalog);
1688 }
1689
1690 return catalog;
1691 }
1692
1693 private class InternalPrimaryIndex<PK, E> extends PrimaryIndex<PK, E> {
1694
1695 private final PersistEntityBinding entityBinding;
1696
1697 InternalPrimaryIndex(final Database database,
1698 final Class<PK> keyClass,
1699 final PersistKeyBinding keyBinding,
1700 final Class<E> entityClass,
1701 final PersistEntityBinding entityBinding)
1702 throws DatabaseException {
1703
1704 super(database, keyClass, keyBinding, entityClass, entityBinding);
1705 this.entityBinding = entityBinding;
1706 }
1707
1708 void refresh(final PersistCatalog newCatalog) {
1709 entityBinding.refresh(newCatalog);
1710 }
1711
1712 }
1713
1714 private class InternalSecondaryIndex<SK, PK, E>
1715 extends SecondaryIndex<SK, PK, E> {
1716
1717 private final PersistKeyCreator keyCreator;
1718
1719 InternalSecondaryIndex(final SecondaryDatabase database,
1720 final PrimaryIndex<PK, E> primaryIndex,
1721 final Class<SK> secondaryKeyClass,
1722 final PersistKeyBinding secondaryKeyBinding,
1723 final PersistKeyCreator keyCreator)
1724 throws DatabaseException {
1725
1726 super(database, null /*keysDatabase*/, primaryIndex,
1727 secondaryKeyClass, secondaryKeyBinding);
1728 this.keyCreator = keyCreator;
1729 }
1730
1731 void refresh(final PersistCatalog newCatalog) {
1732 keyCreator.refresh(newCatalog);
1733 }
1734
1735 }
1736
1737 TransactionConfig getAutoCommitTxnConfig() {
1738 return autoCommitTxnConfig;
1739 }
1740
1741 }