Search in sources :

Example 6 with DatastoreIdentifier

use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.

the class SelectStatement method join.

@Override
public SQLTable join(JoinType joinType, SQLTable sourceTable, Table target, String targetAlias, String tableGrpName, BooleanExpression joinCondition, boolean applyToUnions) {
    invalidateStatement();
    // Create the SQLTable to join to.
    if (tables == null) {
        tables = new HashMap();
    }
    if (tableGrpName == null) {
        tableGrpName = "Group" + tableGroups.size();
    }
    if (targetAlias == null) {
        targetAlias = namer.getAliasForTable(this, target, tableGrpName);
    }
    if (sourceTable == null) {
        sourceTable = primaryTable;
    }
    DatastoreIdentifier targetId = rdbmsMgr.getIdentifierFactory().newTableIdentifier(targetAlias);
    SQLTable targetTbl = new SQLTable(this, target, targetId, tableGrpName);
    putSQLTableInGroup(targetTbl, tableGrpName, joinType);
    addJoin(joinType, sourceTable, targetTbl, joinCondition, null);
    if (unions != null && applyToUnions) {
        // Apply the join to all unions
        Iterator<SelectStatement> unionIter = unions.iterator();
        while (unionIter.hasNext()) {
            SelectStatement stmt = unionIter.next();
            stmt.join(joinType, sourceTable, target, targetAlias, tableGrpName, joinCondition, true);
        }
    }
    return targetTbl;
}
Also used : HashMap(java.util.HashMap) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier)

Example 7 with DatastoreIdentifier

use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.

the class SelectStatement method join.

@Override
public SQLTable join(JoinType joinType, SQLTable sourceTable, JavaTypeMapping sourceMapping, JavaTypeMapping sourceParentMapping, Table target, String targetAlias, JavaTypeMapping targetMapping, JavaTypeMapping targetParentMapping, Object[] discrimValues, String tableGrpName, boolean applyToUnions, SQLJoin parentJoin) {
    invalidateStatement();
    // Create the SQLTable to join to.
    if (tables == null) {
        tables = new HashMap();
    }
    if (tableGrpName == null) {
        tableGrpName = "Group" + tableGroups.size();
    }
    if (targetAlias == null) {
        targetAlias = namer.getAliasForTable(this, target, tableGrpName);
    }
    if (sourceTable == null) {
        sourceTable = primaryTable;
    }
    DatastoreIdentifier targetId = rdbmsMgr.getIdentifierFactory().newTableIdentifier(targetAlias);
    SQLTable targetTbl = new SQLTable(this, target, targetId, tableGrpName);
    putSQLTableInGroup(targetTbl, tableGrpName, joinType);
    // Generate the join condition to use
    BooleanExpression joinCondition = getJoinConditionForJoin(sourceTable, sourceMapping, sourceParentMapping, targetTbl, targetMapping, targetParentMapping, discrimValues);
    addJoin(joinType, sourceTable, targetTbl, joinCondition, parentJoin);
    if (unions != null && applyToUnions) {
        // Apply the join to all unions
        Iterator<SelectStatement> unionIter = unions.iterator();
        while (unionIter.hasNext()) {
            SelectStatement stmt = unionIter.next();
            stmt.join(joinType, sourceTable, sourceMapping, sourceParentMapping, target, targetAlias, targetMapping, targetParentMapping, discrimValues, tableGrpName, true, parentJoin);
        }
    }
    return targetTbl;
}
Also used : BooleanExpression(org.datanucleus.store.rdbms.sql.expression.BooleanExpression) HashMap(java.util.HashMap) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier)

Example 8 with DatastoreIdentifier

use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.

the class SelectStatement method addOrderingColumnsToSelect.

/**
 * Convenience method to add any necessary columns to the SELECT that are needed
 * by the ordering constraint.
 */
protected void addOrderingColumnsToSelect() {
    if (// Don't do this for subqueries, since we will be selecting just the necessary column(s)
    orderingExpressions != null && parent == null) {
        // Add any ordering columns to the SELECT
        DatastoreAdapter dba = getDatastoreAdapter();
        if (dba.supportsOption(DatastoreAdapter.ORDERBY_USING_SELECT_COLUMN_INDEX)) {
            // Order using the indexes of the ordering columns in the SELECT
            orderingColumnIndexes = new int[orderingExpressions.length];
            // Add the ordering columns to the selected list, saving the positions
            for (int i = 0; i < orderingExpressions.length; ++i) {
                orderingColumnIndexes[i] = selectItem(orderingExpressions[i].toSQLText(), null, !aggregated);
                if (unions != null && allowUnions) {
                    Iterator<SelectStatement> iterator = unions.iterator();
                    while (iterator.hasNext()) {
                        SelectStatement stmt = iterator.next();
                        stmt.selectItem(orderingExpressions[i].toSQLText(), null, !aggregated);
                    }
                }
            }
        } else if (dba.supportsOption(DatastoreAdapter.INCLUDE_ORDERBY_COLS_IN_SELECT)) {
            // Order using column aliases "NUCORDER{i}"
            for (int i = 0; i < orderingExpressions.length; ++i) {
                if (orderingExpressions[i] instanceof ResultAliasExpression) {
                // Nothing to do since this is ordering by a result alias
                } else if (orderingExpressions[i].getNumberOfSubExpressions() == 1 || aggregated) {
                    String orderExprAlias = rdbmsMgr.getIdentifierFactory().getIdentifierInAdapterCase("NUCORDER" + i);
                    if (unions != null && allowUnions) {
                        Iterator<SelectStatement> iterator = unions.iterator();
                        while (iterator.hasNext()) {
                            SelectStatement stmt = iterator.next();
                            stmt.selectItem(orderingExpressions[i].toSQLText(), aggregated ? null : orderExprAlias, !aggregated);
                        }
                    }
                    selectItem(orderingExpressions[i].toSQLText(), aggregated ? null : orderExprAlias, !aggregated);
                } else {
                    JavaTypeMapping m = orderingExpressions[i].getJavaTypeMapping();
                    ColumnMapping[] mappings = m.getColumnMappings();
                    for (int j = 0; j < mappings.length; j++) {
                        String alias = rdbmsMgr.getIdentifierFactory().getIdentifierInAdapterCase("NUCORDER" + i + "_" + j);
                        DatastoreIdentifier aliasId = rdbmsMgr.getIdentifierFactory().newColumnIdentifier(alias);
                        SQLColumn col = new SQLColumn(orderingExpressions[i].getSQLTable(), mappings[j].getColumn(), aliasId);
                        selectItem(new SQLText(col.getColumnSelectString()), alias, !aggregated);
                        if (unions != null && allowUnions) {
                            Iterator<SelectStatement> iterator = unions.iterator();
                            while (iterator.hasNext()) {
                                SelectStatement stmt = iterator.next();
                                stmt.selectItem(new SQLText(col.getColumnSelectString()), alias, !aggregated);
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : ResultAliasExpression(org.datanucleus.store.rdbms.sql.expression.ResultAliasExpression) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) ColumnMapping(org.datanucleus.store.rdbms.mapping.column.ColumnMapping)

Example 9 with DatastoreIdentifier

use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.

the class TableImpl method validateColumns.

/**
 * Utility to validate the columns of the table.
 * Will throw a MissingColumnException if a column is not found (and is not required to auto create it)
 * @param conn Connection to use for validation
 * @param validateColumnStructure Whether to validate down to the structure of the columns, or just their existence
 * @param autoCreate Whether to auto create any missing columns
 * @param autoCreateErrors Exceptions found in the "auto-create" process
 * @return Whether it validates
 * @throws SQLException Thrown if an error occurs in the validation process
 */
public boolean validateColumns(Connection conn, boolean validateColumnStructure, boolean autoCreate, Collection autoCreateErrors) throws SQLException {
    Map<DatastoreIdentifier, Column> unvalidated = new HashMap(columnsByIdentifier);
    List<StoreSchemaData> tableColInfo = storeMgr.getColumnInfoForTable(this, conn);
    Iterator i = tableColInfo.iterator();
    while (i.hasNext()) {
        RDBMSColumnInfo ci = (RDBMSColumnInfo) i.next();
        // Create an identifier to use for the real column - use "CUSTOM" because we don't want truncation
        DatastoreIdentifier colIdentifier = storeMgr.getIdentifierFactory().newColumnIdentifier(ci.getColumnName(), this.storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(String.class), null, true);
        Column col = unvalidated.get(colIdentifier);
        if (col != null) {
            if (validateColumnStructure) {
                col.initializeColumnInfoFromDatastore(ci);
                col.validate(ci);
                unvalidated.remove(colIdentifier);
            } else {
                unvalidated.remove(colIdentifier);
            }
        }
    }
    if (unvalidated.size() > 0) {
        if (autoCreate) {
            // Add all missing columns
            List<String> stmts = new ArrayList<>();
            Iterator<Map.Entry<DatastoreIdentifier, Column>> columnsIter = unvalidated.entrySet().iterator();
            while (columnsIter.hasNext()) {
                Map.Entry<DatastoreIdentifier, Column> entry = columnsIter.next();
                Column col = entry.getValue();
                String addColStmt = dba.getAddColumnStatement(this, col);
                stmts.add(addColStmt);
            }
            try {
                executeDdlStatementList(stmts, conn);
            } catch (SQLException sqle) {
                if (autoCreateErrors != null) {
                    autoCreateErrors.add(sqle);
                } else {
                    throw sqle;
                }
            }
            // Invalidate the cached information for this table since it now has a new column
            storeMgr.invalidateColumnInfoForTable(this);
        } else {
            MissingColumnException mce = new MissingColumnException(this, unvalidated.values());
            if (autoCreateErrors != null) {
                autoCreateErrors.add(mce);
            } else {
                throw mce;
            }
        }
    }
    state = TABLE_STATE_VALIDATED;
    return true;
}
Also used : RDBMSColumnInfo(org.datanucleus.store.rdbms.schema.RDBMSColumnInfo) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) MissingColumnException(org.datanucleus.store.rdbms.exceptions.MissingColumnException) ArrayList(java.util.ArrayList) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) Iterator(java.util.Iterator) StoreSchemaData(org.datanucleus.store.schema.StoreSchemaData) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with DatastoreIdentifier

use of org.datanucleus.store.rdbms.identifier.DatastoreIdentifier in project datanucleus-rdbms by datanucleus.

the class TableImpl method getExistingIndices.

/**
 * Accessor for indices on the actual table.
 * @param conn The JDBC Connection
 * @return Map of indices (keyed by the index name)
 * @throws SQLException Thrown when an error occurs in the JDBC call.
 */
private Map<DatastoreIdentifier, Index> getExistingIndices(Connection conn) throws SQLException {
    Map<DatastoreIdentifier, Index> indicesByName = new HashMap<>();
    if (tableExistsInDatastore(conn)) {
        StoreSchemaHandler handler = storeMgr.getSchemaHandler();
        RDBMSTableIndexInfo tableIndexInfo = (RDBMSTableIndexInfo) handler.getSchemaData(conn, RDBMSSchemaHandler.TYPE_INDICES, new Object[] { this });
        IdentifierFactory idFactory = storeMgr.getIdentifierFactory();
        Iterator indexIter = tableIndexInfo.getChildren().iterator();
        while (indexIter.hasNext()) {
            // No idea of why this was being used, so commented out (H2 v2 fails if enabled)
            // short idxType = ((Short)indexInfo.getProperty("type")).shortValue();
            // if (idxType == DatabaseMetaData.tableIndexStatistic)
            // {
            // // Ignore
            // continue;
            // }
            IndexInfo indexInfo = (IndexInfo) indexIter.next();
            String indexName = (String) indexInfo.getProperty("index_name");
            DatastoreIdentifier indexIdentifier = idFactory.newIdentifier(IdentifierType.CANDIDATE_KEY, indexName);
            Index idx = indicesByName.get(indexIdentifier);
            if (idx == null) {
                boolean isUnique = !((Boolean) indexInfo.getProperty("non_unique")).booleanValue();
                idx = new Index(this, isUnique, null);
                idx.setName(indexName);
                indicesByName.put(indexIdentifier, idx);
            }
            // Set the column
            int colSeq = ((Short) indexInfo.getProperty("ordinal_position")).shortValue() - 1;
            DatastoreIdentifier colName = idFactory.newIdentifier(IdentifierType.COLUMN, (String) indexInfo.getProperty("column_name"));
            Column col = columnsByIdentifier.get(colName);
            if (col != null) {
                idx.setColumn(colSeq, col);
            }
        }
    }
    return indicesByName;
}
Also used : HashMap(java.util.HashMap) RDBMSTableIndexInfo(org.datanucleus.store.rdbms.schema.RDBMSTableIndexInfo) Index(org.datanucleus.store.rdbms.key.Index) StoreSchemaHandler(org.datanucleus.store.schema.StoreSchemaHandler) RDBMSTableIndexInfo(org.datanucleus.store.rdbms.schema.RDBMSTableIndexInfo) IndexInfo(org.datanucleus.store.rdbms.schema.IndexInfo) IdentifierFactory(org.datanucleus.store.rdbms.identifier.IdentifierFactory) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) Iterator(java.util.Iterator)

Aggregations

DatastoreIdentifier (org.datanucleus.store.rdbms.identifier.DatastoreIdentifier)45 IdentifierFactory (org.datanucleus.store.rdbms.identifier.IdentifierFactory)19 HashMap (java.util.HashMap)18 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)12 ColumnMetaData (org.datanucleus.metadata.ColumnMetaData)11 Iterator (java.util.Iterator)10 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)10 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)9 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)8 MacroString (org.datanucleus.util.MacroString)6 ArrayList (java.util.ArrayList)5 NucleusException (org.datanucleus.exceptions.NucleusException)5 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)4 Index (org.datanucleus.store.rdbms.key.Index)4 RDBMSColumnInfo (org.datanucleus.store.rdbms.schema.RDBMSColumnInfo)4 StoreSchemaHandler (org.datanucleus.store.schema.StoreSchemaHandler)4 SQLException (java.sql.SQLException)3 HashSet (java.util.HashSet)3 List (java.util.List)3 Map (java.util.Map)3