use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project tests by datanucleus.
the class IdentifierFactoryTest method testJPA.
/**
* Tests for JPAIdentifierFactory.
*/
public void testJPA() {
RDBMSStoreManager srm = (RDBMSStoreManager) storeMgr;
IdentifierFactory idFactory = null;
ClassLoaderResolver clr = new ClassLoaderResolverImpl();
try {
JDOPersistenceManagerFactory thePMF = (JDOPersistenceManagerFactory) pmf;
Map props = new HashMap();
Configuration conf = getConfigurationForPMF(thePMF);
if (conf.getStringProperty("datanucleus.mapping.Catalog") != null) {
props.put("DefaultCatalog", conf.getStringProperty("datanucleus.mapping.Catalog"));
}
if (conf.getStringProperty("datanucleus.mapping.Schema") != null) {
props.put("DefaultSchema", conf.getStringProperty("datanucleus.mapping.Schema"));
}
if (conf.getStringProperty("datanucleus.identifier.case") != null) {
props.put("RequiredCase", conf.getStringProperty("datanucleus.identifier.case"));
} else {
props.put("RequiredCase", srm.getDefaultIdentifierCase());
}
if (conf.getStringProperty("datanucleus.identifier.wordSeparator") != null) {
props.put("WordSeparator", conf.getStringProperty("datanucleus.identifier.wordSeparator"));
}
if (conf.getStringProperty("datanucleus.identifier.tablePrefix") != null) {
props.put("TablePrefix", conf.getStringProperty("datanucleus.identifier.tablePrefix"));
}
if (conf.getStringProperty("datanucleus.identifier.tableSuffix") != null) {
props.put("TableSuffix", conf.getStringProperty("datanucleus.identifier.tableSuffix"));
}
Class cls = Class.forName("org.datanucleus.store.rdbms.identifier.JPAIdentifierFactory");
Class[] argTypes = new Class[] { DatastoreAdapter.class, ClassLoaderResolver.class, Map.class };
Object[] args = new Object[] { srm.getDatastoreAdapter(), srm.getNucleusContext().getClassLoaderResolver(null), props };
idFactory = (IdentifierFactory) ClassUtils.newInstance(cls, argTypes, args);
} catch (Exception e) {
fail("Error creating JPAIdentifierFactory : " + e.getMessage());
}
// Table identifiers
// a). generated name shorter than max length
DatastoreIdentifier id = idFactory.newIdentifier(IdentifierType.TABLE, "MyClass");
assertTrue("newIdentifier(TABLE, String) has generated an incorrect name : " + id.getName(), "MYCLASS".equalsIgnoreCase(id.getName()));
// b). specified name shorter than max length
id = idFactory.newTableIdentifier("MY_TABLE_NAME");
assertTrue("newDatastoreContainerIdentifier(String) has returned an incorrect name when should have used the supplied name " + id.getName(), "MY_TABLE_NAME".equalsIgnoreCase(id.getName()));
// c). name specified via ClassMetaData
AbstractClassMetaData managerCMD = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass("org.jpox.samples.models.company.Manager", clr);
id = idFactory.newTableIdentifier(managerCMD);
assertTrue("newDatastoreContainerIdentifier(clr, ClassMetaData) has returned an incorrect generated name " + id.getName(), "MANAGER".equalsIgnoreCase(id.getName()));
// d). name specified via ClassMetaData
AbstractMemberMetaData fmd = managerCMD.getMetaDataForMember("subordinates");
id = idFactory.newTableIdentifier(fmd);
assertTrue("newDatastoreContainerIdentifier(clr, AbstractMemberMetaData) has returned an incorrect generated name " + id.getName(), "MANAGER_EMPLOYEE".equalsIgnoreCase(id.getName()));
// Column identifiers
// a). generated name shorter than max length
id = idFactory.newIdentifier(IdentifierType.COLUMN, "myField");
assertTrue("newIdentifier(COLUMN, String) has generated an incorrect name : " + id.getName(), "MYFIELD".equalsIgnoreCase(id.getName()));
// b). specified name shorter than max length
id = idFactory.newColumnIdentifier("MY_COLUMN_NAME");
assertTrue("newColumnIdentifier(String) has returned an incorrect name when should have used the supplied name " + id.getName(), "MY_COLUMN_NAME".equalsIgnoreCase(id.getName()));
// c). Discriminator column identifier
id = idFactory.newDiscriminatorFieldIdentifier();
assertTrue("newDiscriminatorFieldIdentifier() has returned an incorrect name : " + id.getName(), "DTYPE".equalsIgnoreCase(id.getName()));
// d). Version column identifier
id = idFactory.newVersionFieldIdentifier();
assertTrue("newVersionFieldIdentifier() has returned an incorrect name : " + id.getName(), "VERSION".equalsIgnoreCase(id.getName()));
// e). Index (ordering) column identifier
id = idFactory.newIndexFieldIdentifier(fmd);
assertTrue("newIndexFieldIdentifier() has returned an incorrect name : " + id.getName(), "SUBORDINATES_ORDER".equalsIgnoreCase(id.getName()));
// f). Adapter Index column identifier
id = idFactory.newAdapterIndexFieldIdentifier();
assertTrue("newAdapterIndexFieldIdentifier() has returned an incorrect name : " + id.getName(), "IDX".equalsIgnoreCase(id.getName()));
AbstractMemberMetaData[] relatedMmds = fmd.getRelatedMemberMetaData(clr);
// g). join table owner column identifier (1-N bi JoinTable)
DatastoreIdentifier destId = idFactory.newColumnIdentifier("MANAGER_ID");
id = idFactory.newJoinTableFieldIdentifier(fmd, relatedMmds != null ? relatedMmds[0] : null, destId, false, FieldRole.ROLE_OWNER);
assertTrue("newJoinTableFieldIdentifier(OWNER) has returned an incorrect generated name " + id.getName(), "MANAGER_MANAGER_ID".equalsIgnoreCase(id.getName()));
// h). join table element column identifier (1-N bi JoinTable)
destId = idFactory.newColumnIdentifier("EMPLOYEE_ID");
id = idFactory.newJoinTableFieldIdentifier(fmd, relatedMmds != null ? relatedMmds[0] : null, destId, false, FieldRole.ROLE_COLLECTION_ELEMENT);
assertTrue("newJoinTableFieldIdentifier(ELEMENT) has returned an incorrect generated name " + id.getName(), "SUBORDINATES_EMPLOYEE_ID".equalsIgnoreCase(id.getName()));
// i). FK owner column identifier (1-N bi FK)
AbstractMemberMetaData deptsFMD = managerCMD.getMetaDataForMember("departments");
AbstractMemberMetaData[] deptsRelatedMmds = deptsFMD.getRelatedMemberMetaData(clr);
destId = idFactory.newColumnIdentifier("MANAGER_ID");
id = idFactory.newForeignKeyFieldIdentifier(deptsFMD, deptsRelatedMmds != null ? deptsRelatedMmds[0] : null, destId, true, FieldRole.ROLE_OWNER);
assertTrue("newForeignKeyFieldIdentifier(OWNER) has returned an incorrect generated name " + id.getName(), "MANAGER_MANAGER_ID".equalsIgnoreCase(id.getName()));
// Primary key identifiers
// Index identifiers
// Foreign key identifiers
// Candidate key identifiers
// Sequence identifiers
}
use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.
the class RDBMSStoreManager method getManagedTables.
/**
* Convenience accessor of the Table objects managed in this datastore at this point.
* @param catalog Name of the catalog to restrict the collection by (or null to not restrict)
* @param schema Name of the schema to restrict the collection by (or null to not restrict)
* @return Collection of tables
*/
public Collection<Table> getManagedTables(String catalog, String schema) {
if (storeDataMgr == null) {
return Collections.EMPTY_SET;
}
Collection<Table> tables = new HashSet<>();
for (StoreData sd : storeDataMgr.getManagedStoreData()) {
if (sd.getTable() != null) {
// Catalog/Schema match if either managed table not set, or input requirements not set
DatastoreIdentifier identifier = ((Table) sd.getTable()).getIdentifier();
boolean catalogMatches = true;
boolean schemaMatches = true;
if (catalog != null && identifier.getCatalogName() != null && !catalog.equals(identifier.getCatalogName())) {
catalogMatches = false;
}
if (schema != null && identifier.getSchemaName() != null && !schema.equals(identifier.getSchemaName())) {
schemaMatches = false;
}
if (catalogMatches && schemaMatches) {
tables.add((Table) sd.getTable());
}
}
}
return tables;
}
use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.
the class RDBMSQueryUtils method getStatementForCandidates.
/**
* Method to return a statement selecting the candidate table(s) required to cover all possible types for this candidates inheritance strategy.
* @param storeMgr RDBMS StoreManager
* @param parentStmt Parent statement (if there is one)
* @param cmd Metadata for the class
* @param clsMapping Mapping for the results of the statement
* @param ec ExecutionContext
* @param candidateCls Candidate class
* @param subclasses Whether to create a statement for subclasses of the candidate too
* @param result The result clause
* @param candidateAlias alias for the candidate (if any)
* @param candidateTableGroupName TableGroup name for the candidate (if any)
* @param options Any options for the statement for getting candidates. See SelectStatementGenerator for some options.
* @return The SQLStatement
* @throws NucleusException if there are no tables for concrete classes in this query (hence would return null)
*/
public static SelectStatement getStatementForCandidates(RDBMSStoreManager storeMgr, SQLStatement parentStmt, AbstractClassMetaData cmd, StatementClassMapping clsMapping, ExecutionContext ec, Class candidateCls, boolean subclasses, String result, String candidateAlias, String candidateTableGroupName, Set<String> options) {
SelectStatement stmt = null;
DatastoreIdentifier candidateAliasId = null;
if (candidateAlias != null) {
candidateAliasId = storeMgr.getIdentifierFactory().newTableIdentifier(candidateAlias);
}
ClassLoaderResolver clr = ec.getClassLoaderResolver();
List<DatastoreClass> candidateTables = new ArrayList<>();
if (cmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE) {
DatastoreClass candidateTable = storeMgr.getDatastoreClass(cmd.getFullClassName(), clr);
if (candidateTable != null) {
candidateTables.add(candidateTable);
}
if (subclasses) {
Collection<String> subclassNames = storeMgr.getSubClassesForClass(cmd.getFullClassName(), subclasses, clr);
if (subclassNames != null) {
Iterator<String> subclassIter = subclassNames.iterator();
while (subclassIter.hasNext()) {
String subclassName = subclassIter.next();
DatastoreClass tbl = storeMgr.getDatastoreClass(subclassName, clr);
if (tbl != null) {
candidateTables.add(tbl);
}
}
}
}
Iterator<DatastoreClass> iter = candidateTables.iterator();
int maxClassNameLength = cmd.getFullClassName().length();
while (iter.hasNext()) {
DatastoreClass cls = iter.next();
String className = cls.getType();
if (className.length() > maxClassNameLength) {
maxClassNameLength = className.length();
}
}
iter = candidateTables.iterator();
while (iter.hasNext()) {
DatastoreClass cls = iter.next();
SelectStatement tblStmt = new SelectStatement(parentStmt, storeMgr, cls, candidateAliasId, candidateTableGroupName);
tblStmt.setClassLoaderResolver(clr);
tblStmt.setCandidateClassName(cls.getType());
// Add SELECT of dummy column accessible as "DN_TYPE" containing the classname
JavaTypeMapping m = storeMgr.getMappingManager().getMapping(String.class);
String nuctypeName = cls.getType();
if (maxClassNameLength > nuctypeName.length()) {
nuctypeName = StringUtils.leftAlignedPaddedString(nuctypeName, maxClassNameLength);
}
StringLiteral lit = new StringLiteral(tblStmt, m, nuctypeName, null);
tblStmt.select(lit, UnionStatementGenerator.DN_TYPE_COLUMN);
if (stmt == null) {
stmt = tblStmt;
} else {
stmt.union(tblStmt);
}
}
if (clsMapping != null) {
clsMapping.setNucleusTypeColumnName(UnionStatementGenerator.DN_TYPE_COLUMN);
}
} else {
// "new-table", "superclass-table", "subclass-table"
List<Class> candidateClasses = new ArrayList<>();
if (ClassUtils.isReferenceType(candidateCls)) {
// Persistent interface, so find all persistent implementations
String[] clsNames = storeMgr.getNucleusContext().getMetaDataManager().getClassesImplementingInterface(candidateCls.getName(), clr);
for (int i = 0; i < clsNames.length; i++) {
Class cls = clr.classForName(clsNames[i]);
DatastoreClass table = storeMgr.getDatastoreClass(clsNames[i], clr);
candidateClasses.add(cls);
candidateTables.add(table);
AbstractClassMetaData implCmd = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(cls, clr);
if (implCmd.getIdentityType() != cmd.getIdentityType()) {
throw new NucleusUserException("You are querying an interface (" + cmd.getFullClassName() + ") " + "yet one of its implementations (" + implCmd.getFullClassName() + ") uses a different identity type!");
} else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
if (cmd.getPKMemberPositions().length != implCmd.getPKMemberPositions().length) {
throw new NucleusUserException("You are querying an interface (" + cmd.getFullClassName() + ") " + "yet one of its implementations (" + implCmd.getFullClassName() + ") has a different number of PK members!");
}
}
}
} else {
DatastoreClass candidateTable = storeMgr.getDatastoreClass(cmd.getFullClassName(), clr);
if (candidateTable != null) {
// Candidate has own table
candidateClasses.add(candidateCls);
candidateTables.add(candidateTable);
} else {
// Candidate stored in subclass tables
AbstractClassMetaData[] cmds = storeMgr.getClassesManagingTableForClass(cmd, clr);
if (cmds != null && cmds.length > 0) {
for (int i = 0; i < cmds.length; i++) {
DatastoreClass table = storeMgr.getDatastoreClass(cmds[i].getFullClassName(), clr);
Class cls = clr.classForName(cmds[i].getFullClassName());
candidateClasses.add(cls);
candidateTables.add(table);
}
} else {
throw new UnsupportedOperationException("No tables for query of " + cmd.getFullClassName());
}
}
}
for (int i = 0; i < candidateTables.size(); i++) {
DatastoreClass tbl = candidateTables.get(i);
Class cls = candidateClasses.get(i);
SelectStatementGenerator stmtGen = null;
if (tbl.getSurrogateMapping(SurrogateColumnType.DISCRIMINATOR, true) != null || QueryUtils.resultHasOnlyAggregates(result)) {
// Either has a discriminator, or only selecting aggregates so need single select
stmtGen = new DiscriminatorStatementGenerator(storeMgr, clr, cls, subclasses, candidateAliasId, candidateTableGroupName);
stmtGen.setOption(SelectStatementGenerator.OPTION_RESTRICT_DISCRIM);
if (options != null) {
if (options.contains(SelectStatementGenerator.OPTION_DONT_RESTRICT_DISCRIM)) {
// User explicitly requested no restriction on the discriminator
stmtGen.unsetOption(SelectStatementGenerator.OPTION_RESTRICT_DISCRIM);
}
for (String option : options) {
stmtGen.setOption(option);
}
}
} else {
// No discriminator, so try to identify using UNIONs (hopefully one per class)
stmtGen = new UnionStatementGenerator(storeMgr, clr, cls, subclasses, candidateAliasId, candidateTableGroupName);
if (options != null) {
for (String option : options) {
stmtGen.setOption(option);
}
}
if (result == null) {
// Returning one row per candidate so include distinguisher column
stmtGen.setOption(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
if (clsMapping != null) {
clsMapping.setNucleusTypeColumnName(UnionStatementGenerator.DN_TYPE_COLUMN);
}
}
}
stmtGen.setParentStatement(parentStmt);
SelectStatement tblStmt = stmtGen.getStatement(ec);
if (stmt == null) {
stmt = tblStmt;
} else {
stmt.union(tblStmt);
}
}
}
return stmt;
}
use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.
the class RDBMSSchemaHandler method getTableKeyInRDBMSSchemaInfo.
/**
* Convenience accessor for the key that we use to store a tables information in RDBMSSchemaInfo.
* @param catalog The catalog name
* @param schema The schema name
* @param table The table name
* @return Its key (fully-qualified table name)
*/
private String getTableKeyInRDBMSSchemaInfo(String catalog, String schema, String table) {
DatastoreIdentifier fullyQualifiedTableName = rdbmsStoreMgr.getIdentifierFactory().newTableIdentifier(table);
fullyQualifiedTableName.setCatalogName(catalog);
fullyQualifiedTableName.setSchemaName(schema);
return fullyQualifiedTableName.getFullyQualifiedName(true);
}
use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.
the class TableImpl method getExistingPrimaryKeys.
/**
* Accessor for the primary keys for this table in the datastore.
* @param conn The JDBC Connection
* @return Map of primary keys
* @throws SQLException Thrown when an error occurs in the JDBC call.
*/
private Map<DatastoreIdentifier, PrimaryKey> getExistingPrimaryKeys(Connection conn) throws SQLException {
Map<DatastoreIdentifier, PrimaryKey> primaryKeysByName = new HashMap<>();
if (tableExistsInDatastore(conn)) {
StoreSchemaHandler handler = storeMgr.getSchemaHandler();
RDBMSTablePKInfo tablePkInfo = (RDBMSTablePKInfo) handler.getSchemaData(conn, RDBMSSchemaHandler.TYPE_PKS, new Object[] { this });
IdentifierFactory idFactory = storeMgr.getIdentifierFactory();
Iterator pkColsIter = tablePkInfo.getChildren().iterator();
while (pkColsIter.hasNext()) {
PrimaryKeyInfo pkInfo = (PrimaryKeyInfo) pkColsIter.next();
String pkName = (String) pkInfo.getProperty("pk_name");
DatastoreIdentifier pkIdentifier;
if (pkName == null) {
pkIdentifier = idFactory.newPrimaryKeyIdentifier(this);
} else {
pkIdentifier = idFactory.newIdentifier(IdentifierType.COLUMN, pkName);
}
PrimaryKey pk = primaryKeysByName.get(pkIdentifier);
if (pk == null) {
pk = new PrimaryKey(this);
pk.setName(pkIdentifier.getName());
primaryKeysByName.put(pkIdentifier, pk);
}
int keySeq = (((Short) pkInfo.getProperty("key_seq")).shortValue()) - 1;
String colName = (String) pkInfo.getProperty("column_name");
DatastoreIdentifier colIdentifier = idFactory.newIdentifier(IdentifierType.COLUMN, colName);
Column col = columnsByIdentifier.get(colIdentifier);
if (col == null) {
throw new UnexpectedColumnException(this.toString(), colIdentifier.getName(), this.getSchemaName(), this.getCatalogName());
}
pk.setColumn(keySeq, col);
}
}
return primaryKeysByName;
}
Aggregations