Package org.datanucleus.store.mapped

Examples of org.datanucleus.store.mapped.MappedStoreManager


     */
    public static void prepareStatementForExecution(PreparedStatement ps, Query query, boolean applyTimeout)
    throws SQLException
    {
        NucleusContext nucleusCtx = query.getExecutionContext().getNucleusContext();
        MappedStoreManager storeMgr = (MappedStoreManager)nucleusCtx.getStoreManager();
        PersistenceConfiguration conf = nucleusCtx.getPersistenceConfiguration();

        if (applyTimeout)
        {
            Integer timeout = query.getDatastoreReadTimeoutMillis();
            if (timeout != null && timeout > 0)
            {
                ps.setQueryTimeout(timeout/1000);
            }
        }

        // Apply any fetch size
        int fetchSize = 0;
        if (query.getFetchPlan().getFetchSize() > 0)
        {
            // FetchPlan has a size set so use that
            fetchSize = query.getFetchPlan().getFetchSize();
        }
        if (storeMgr.getDatastoreAdapter().supportsQueryFetchSize(fetchSize))
        {
            ps.setFetchSize(fetchSize);
        }

        // Apply any fetch direction
View Full Code Here


     */
    protected ResultObjectFactory getResultObjectFactoryForCandidateClass(ResultSet rs)
    throws SQLException
    {
        ClassLoaderResolver clr = ec.getClassLoaderResolver();
        MappedStoreManager storeMgr = (MappedStoreManager)ec.getStoreManager();
        DatastoreAdapter dba = storeMgr.getDatastoreAdapter();

        // Create an index listing for ALL (fetchable) fields in the result class.
        final AbstractClassMetaData candidateCmd = ec.getMetaDataManager().getMetaDataForClass(candidateClass, clr);
        int fieldCount = candidateCmd.getNoOfManagedMembers() + candidateCmd.getNoOfInheritedManagedMembers();
        Map columnFieldNumberMap = new HashMap(); // Map of field numbers keyed by the column name
        stmtMappings = new StatementMappingIndex[fieldCount];
        DatastoreClass tbl = storeMgr.getDatastoreClass(candidateClass.getName(), clr);
        for (int fieldNumber = 0; fieldNumber < fieldCount; ++fieldNumber)
        {
            AbstractMemberMetaData fmd = candidateCmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber);
            String fieldName = fmd.getName();
            Class fieldType = fmd.getType();

            JavaTypeMapping m = null;
            if (fmd.getPersistenceModifier() != FieldPersistenceModifier.NONE)
            {
                if (tbl != null)
                {
                    // Get the field mapping from the candidate table
                    m = tbl.getMemberMapping(fmd);
                }
                else
                {
                    // Fall back to generating a mapping for this type - does this ever happen?
                    m = storeMgr.getMappingManager().getMappingWithDatastoreMapping(
                        fieldType, false, false, clr);
                }
                if (m.includeInFetchStatement())
                {
                    // Set mapping for this field since it can potentially be returned from a fetch
                    String columnName = null;
                    if (fmd.getColumnMetaData() != null && fmd.getColumnMetaData().length > 0)
                    {
                        for (int colNum = 0;colNum<fmd.getColumnMetaData().length;colNum++)
                        {
                            columnName = fmd.getColumnMetaData()[colNum].getName();
                            columnFieldNumberMap.put(columnName, Integer.valueOf(fieldNumber));
                        }
                    }
                    else
                    {
                        columnName = storeMgr.getIdentifierFactory().newDatastoreFieldIdentifier(
                            fieldName, ec.getNucleusContext().getTypeManager().isDefaultEmbeddedType(fieldType),
                            FieldRole.ROLE_NONE).getIdentifierName();
                        columnFieldNumberMap.put(columnName, Integer.valueOf(fieldNumber));
                    }
                }
                else
                {
                    // Don't put anything in this position (field has no column in the result set)
                }
            }
            else
            {
                // Don't put anything in this position (field has no column in the result set)
            }
            stmtMappings[fieldNumber] = new StatementMappingIndex(m);
        }
        if (columnFieldNumberMap.size() == 0)
        {
            // None of the fields in the class have columns in the datastore table!
            throw new NucleusUserException(LOCALISER.msg("059030", candidateClass.getName())).setFatal();
        }

        // Generate id column field information for later checking the id is present
        DatastoreClass table = storeMgr.getDatastoreClass(candidateClass.getName(), clr);
        PersistableMapping idMapping = (PersistableMapping)table.getIdMapping();
        String[] idColNames = new String[idMapping.getNumberOfDatastoreMappings()];
        boolean[] idColMissing = new boolean[idMapping.getNumberOfDatastoreMappings()];
        for (int i=0;i<idMapping.getNumberOfDatastoreMappings();i++)
        {
            DatastoreMapping m = idMapping.getDatastoreMapping(i);
            idColNames[i] = m.getDatastoreField().getIdentifier().toString();
            idColMissing[i] = true;
        }

        // Generate discriminator/version information for later checking they are present
        String discriminatorColName = table.getDiscriminatorMapping(false) != null ?
                table.getDiscriminatorMapping(false).getDatastoreMapping(0).getDatastoreField().getIdentifier().toString() : null;
        String versionColName = table.getVersionMapping(false) != null ?
                table.getVersionMapping(false).getDatastoreMapping(0).getDatastoreField().getIdentifier().toString() : null;
        boolean discrimMissing = (discriminatorColName != null);
        boolean versionMissing = true;
        if (versionColName == null)
        {
            versionMissing = false;
        }

        // Go through the fields of the ResultSet and map to the required fields in the candidate
        // Note that we check the existence of the columns again here even though they were checked at compilation
        // TODO This could be removed from here since its now done at compile time
        ResultSetMetaData rsmd = rs.getMetaData();
        HashSet remainingColumnNames = new HashSet(columnFieldNumberMap.size());
        int colCount = rsmd.getColumnCount();
        int[] datastoreIndex = null;
        int[] versionIndex = null;

        int[] matchedFieldNumbers = new int[colCount];
        int fieldNumberPosition = 0;
        for (int colNum=1; colNum<=colCount; ++colNum)
        {
            String colName = rsmd.getColumnName(colNum);

            // Find the field for this column
            int fieldNumber = -1;
            Integer fieldNum = (Integer)columnFieldNumberMap.get(colName);
            if (fieldNum == null)
            {
                // Try column name in lowercase
                fieldNum = (Integer)columnFieldNumberMap.get(colName.toLowerCase());
                if (fieldNum == null)
                {
                    // Try column name in UPPERCASE
                    fieldNum = (Integer)columnFieldNumberMap.get(colName.toUpperCase());
                }
            }

            if (fieldNum != null)
            {
                fieldNumber = fieldNum.intValue();
            }
            if (fieldNumber >= 0)
            {
                int[] exprIndices = null;
                if (stmtMappings[fieldNumber].getColumnPositions() != null)
                {
                    exprIndices = new int[stmtMappings[fieldNumber].getColumnPositions().length+1];
                    for (int i=0;i<stmtMappings[fieldNumber].getColumnPositions().length;i++)
                    {
                        exprIndices[i] = stmtMappings[fieldNumber].getColumnPositions()[i];
                    }
                    exprIndices[exprIndices.length-1] = colNum;
                }
                else
                {
                    exprIndices = new int[] {colNum};
                }
                stmtMappings[fieldNumber].setColumnPositions(exprIndices);
                remainingColumnNames.remove(colName);
                matchedFieldNumbers[fieldNumberPosition++] = fieldNumber;
            }

            if (versionColName != null && colName.equals(versionColName))
            {
                // Identify the location of the version column
                versionIndex = new int[1];
                versionIndex[0] = colNum;
                versionMissing = false;
            }

            if (candidateCmd.getIdentityType() == IdentityType.DATASTORE)
            {
                // Check for existence of id column, allowing for any RDBMS using quoted identifiers
                if (columnNamesAreTheSame(dba, idColNames[0], colName))
                {
                    datastoreIndex = new int[1];
                    datastoreIndex[0] = colNum;
                    idColMissing[0] = false;
                }
            }
            else if (candidateCmd.getIdentityType() == IdentityType.APPLICATION)
            {
                for (int j=0;j<idColNames.length;j++)
                {
                    // Check for existence of id column, allowing for any RDBMS using quoted identifiers
                    if (columnNamesAreTheSame(dba, idColNames[j], colName))
                    {
                        idColMissing[j] = false;
                    }
                }
            }
            if (discrimMissing && columnNamesAreTheSame(dba, discriminatorColName, colName))
            {
                discrimMissing = false;
            }
            else if (versionMissing && columnNamesAreTheSame(dba, versionColName, colName))
            {
                versionMissing = false;
            }
        }

        // Set the field numbers found to match what we really have
        int[] fieldNumbers = new int[fieldNumberPosition];
        for (int i=0;i<fieldNumberPosition;i++)
        {
            fieldNumbers[i] = matchedFieldNumbers[i];
        }

        if (discrimMissing)
        {
            throw new NucleusUserException(LOCALISER_RDBMS.msg("059014",
                inputSQL, candidateClass.getName(), discriminatorColName));
        }
        if (versionMissing)
        {
            throw new NucleusUserException(LOCALISER_RDBMS.msg("059015",
                inputSQL, candidateClass.getName(), versionColName));
        }
        for (int i=0;i<idColMissing.length;i++)
        {
            if (idColMissing[i])
            {
                throw new NucleusUserException(LOCALISER_RDBMS.msg("059013",
                    inputSQL, candidateClass.getName(), idColNames[i]));
            }
        }

        StatementClassMapping mappingDefinition = new StatementClassMapping();
        for (int i=0;i<fieldNumbers.length;i++)
        {
            mappingDefinition.addMappingForMember(fieldNumbers[i], stmtMappings[fieldNumbers[i]]);
        }
        if (datastoreIndex != null)
        {
            StatementMappingIndex datastoreMappingIdx = new StatementMappingIndex(table.getDatastoreObjectIdMapping());
            datastoreMappingIdx.setColumnPositions(datastoreIndex);
            mappingDefinition.addMappingForMember(StatementClassMapping.MEMBER_DATASTORE_ID, datastoreMappingIdx);
        }
        if (versionIndex != null)
        {
            StatementMappingIndex versionMappingIdx = new StatementMappingIndex(table.getVersionMapping(true));
            versionMappingIdx.setColumnPositions(versionIndex);
            mappingDefinition.addMappingForMember(StatementClassMapping.MEMBER_VERSION, versionMappingIdx);
        }

        return storeMgr.newResultObjectFactory(candidateCmd, mappingDefinition,
            ignoreCache, getFetchPlan(), getCandidateClass());
    }
View Full Code Here

        String compiledSQL = getInputSQL();

        if (candidateClass != null && getType() == Query.SELECT)
        {
            // Perform any sanity checking of input for SELECT queries
            MappedStoreManager storeMgr = (MappedStoreManager)ec.getStoreManager();
            ClassLoaderResolver clr = ec.getClassLoaderResolver();
            AbstractClassMetaData cmd = ec.getMetaDataManager().getMetaDataForClass(candidateClass, clr);
            if (cmd == null)
            {
                throw new ClassNotPersistableException(candidateClass.getName());
            }
            if (cmd.getPersistenceCapableSuperclass() != null)
            {
               // throw new PersistentSuperclassNotAllowedException(candidateClass.getName());
            }

            if (getResultClass() == null)
            {
                // Check the presence of the required columns (id, version, discriminator) in the candidate class
                String selections = compiledSQL.trim().substring(7); // Skip "SELECT "
                int fromStart = selections.indexOf("FROM");
                if (fromStart == -1)
                {
                    fromStart = selections.indexOf("from");
                }
                selections = selections.substring(0, fromStart).trim();
                String[] selectedColumns = StringUtils.split(selections, ",");

                if (selectedColumns == null || selectedColumns.length == 0)
                {
                    throw new NucleusUserException(LOCALISER_RDBMS.msg("059003", compiledSQL));
                }
                if (selectedColumns.length == 1 && selectedColumns[0].trim().equals("*"))
                {
                    // SQL Query using * so just return since all possible columns will be selected
                    return compiledSQL;
                }

                // Generate id column field information for later checking the id is present
                DatastoreClass table = storeMgr.getDatastoreClass(candidateClass.getName(), clr);
                PersistableMapping idMapping = (PersistableMapping)table.getIdMapping();
                String[] idColNames = new String[idMapping.getNumberOfDatastoreMappings()];
                boolean[] idColMissing = new boolean[idMapping.getNumberOfDatastoreMappings()];
                for (int i=0;i<idMapping.getNumberOfDatastoreMappings();i++)
                {
                    DatastoreMapping m = idMapping.getDatastoreMapping(i);
                    idColNames[i] = m.getDatastoreField().getIdentifier().toString();
                    idColMissing[i] = true;
                }

                // Generate discriminator/version information for later checking they are present
                String discriminatorColName = table.getDiscriminatorMapping(false) != null ?
                        table.getDiscriminatorMapping(false).getDatastoreMapping(0).getDatastoreField().getIdentifier().toString() : null;
                String versionColName = table.getVersionMapping(false) != null ?
                        table.getVersionMapping(false).getDatastoreMapping(0).getDatastoreField().getIdentifier().toString() : null;
                boolean discrimMissing = (discriminatorColName != null);
                boolean versionMissing = true;
                if (versionColName == null)
                {
                    versionMissing = false;
                }

                // Go through the selected fields and check the existence of id, version, discriminator cols
                DatastoreAdapter dba = storeMgr.getDatastoreAdapter();
                final AbstractClassMetaData candidateCmd = ec.getMetaDataManager().getMetaDataForClass(candidateClass, clr);
                for (int i = 0; i < selectedColumns.length; i++)
                {
                    String colName = selectedColumns[i].trim();
                    if (colName.indexOf(" AS ") > 0)
View Full Code Here

            ManagedConnection mconn, PreparedStatement ps)
    throws SQLException
    {
        Object datastoreId = null;

        MappedStoreManager storeMgr = (MappedStoreManager)ec.getStoreManager();
        if (((RDBMSAdapter) storeMgr.getDatastoreAdapter()).supportsOption(RDBMSAdapter.GET_GENERATED_KEYS_STATEMENT))
        {
            // Try getGeneratedKeys() method to avoid extra SQL calls (only in more recent JDBC drivers)
            ResultSet rs = null;
            try
            {
                rs = ps.getGeneratedKeys();
                if (rs != null && rs.next())
                {
                    datastoreId = rs.getObject(1);
                }
            }
            catch (Throwable e)
            {
                // Not supported maybe (e.g HSQL), or the driver is too old
            }
            finally
            {
                if (rs != null)
                {
                    rs.close();
                }
            }
        }

        if (datastoreId == null)
        {
            // Not found, so try the native method for retrieving it
            String columnName = null;
            JavaTypeMapping idMapping = table.getIdMapping();
            if (idMapping != null)
            {
                for (int i=0;i<idMapping.getNumberOfDatastoreMappings();i++)
                {
                    Column col = (Column)idMapping.getDatastoreMapping(i).getDatastoreField();
                    if (col.isIdentity())
                    {
                        columnName = col.getIdentifier().toString();
                        break;
                    }
                }
            }
            String autoIncStmt =
                ((RDBMSAdapter)storeMgr.getDatastoreAdapter()).getAutoIncrementStmt((Table)table, columnName);
            PreparedStatement psAutoIncrement = sqlControl.getStatementForQuery(mconn, autoIncStmt);
            ResultSet rs = null;
            try
            {
                rs = sqlControl.executeStatementQuery(mconn, autoIncStmt, psAutoIncrement);
View Full Code Here

            }

            if (value.size() > 0)
            {
                // Add the entries direct to the datastore
                MappedStoreManager storeMgr = datastoreContainer.getStoreManager();
                ((MapStore) storeMgr.getBackingStoreForField(ownerOP.getExecutionContext().getClassLoaderResolver(), mmd, value.getClass())).putAll(ownerOP, value);

                // Create a SCO wrapper with the entries loaded
                replaceFieldWithWrapper(ownerOP, value, false, false);
            }
            else
View Full Code Here

     * @param ownerOP ObjectProvider of the owner
     */
    public void postUpdate(ObjectProvider ownerOP)
    {
        ExecutionContext ec = ownerOP.getExecutionContext();
        MappedStoreManager storeMgr = datastoreContainer.getStoreManager();
        java.util.Map value = (java.util.Map) ownerOP.provideField(mmd.getAbsoluteFieldNumber());
        if (containerIsStoredInSingleColumn())
        {
            // Do nothing when serialised since we are handled in the main request
            if (value != null)
            {
                // Make sure the keys/values are ok for proceeding
                SCOUtils.validateObjectsForWriting(ownerOP, value.keySet());
                SCOUtils.validateObjectsForWriting(ownerOP, value.values());
            }
            return;
        }

        if (value == null)
        {
            // replace null map with empty SCO wrapper
            replaceFieldWithWrapper(ownerOP, null, false, false);
            return;
        }

        if (value instanceof SCOContainer)
        {
            SCOContainer sco = (SCOContainer) value;

            if (ownerOP.getObject() == sco.getOwner() && mmd.getName().equals(sco.getFieldName()))
            {
                // Flush any outstanding updates
                sco.flush();

                return;
            }

            if (sco.getOwner() != null)
            {
                throw new NucleusException("Owned second-class object was somehow assigned to a field other than its owner's").setFatal();
            }
        }

        if (!mmd.isCascadeUpdate())
        {
            // User doesnt want to update by reachability
            if (NucleusLogger.PERSISTENCE.isDebugEnabled())
            {
                NucleusLogger.PERSISTENCE.debug(LOCALISER.msg("007008", mmd.getFullFieldName()));
            }
            return;
        }
        if (NucleusLogger.PERSISTENCE.isDebugEnabled())
        {
            NucleusLogger.PERSISTENCE.debug(LOCALISER.msg("007009", mmd.getFullFieldName()));
        }

        // Update the datastore with this value of map (clear old entries and add new ones)
        // This method could be called in two situations
        // 1). Update a map field of an object, so UpdateRequest is called, which calls here
        // 2). Persist a new object, and it needed to wait til the element was inserted so
        //     goes into dirty state and then flush() triggers UpdateRequest, which comes here
        MapStore store = ((MapStore) storeMgr.getBackingStoreForField(
            ec.getClassLoaderResolver(), mmd, value.getClass()));

        // TODO Consider making this more efficient picking the ones to remove/add
        // e.g use an update() method on the backing store like for CollectionStore
        store.clear(ownerOP);
View Full Code Here

                JavaTypeMapping mapping;
                if (implTypes.length > javaTypeMappings.length)
                {
                    // all mappings stored to the same column(s), so same FK
                    PersistableMapping m = ((PersistableMapping) javaTypeMappings[0]);
                    MappedStoreManager storeMgr = (MappedStoreManager)ec.getStoreManager();
                    mapping = storeMgr.getMappingManager().getMapping(ec.getClassLoaderResolver().classForName(implTypes[i]));
                    for (int j = 0; j < m.getDatastoreMappings().length; j++)
                    {
                        mapping.addDatastoreMapping(m.getDatastoreMappings()[j]);
                    }
                    for (int j = 0; j < m.getJavaTypeMapping().length; j++)
View Full Code Here

        ObjectProvider valueSM = ec.findObjectProvider(value);

        try
        {
            ClassLoaderResolver clr = ec.getClassLoaderResolver();
            MappedStoreManager storeMgr = (MappedStoreManager)ec.getStoreManager();

            // Check if the field is attributed in the datastore
            boolean hasDatastoreAttributedPrimaryKeyValues = hasDatastoreAttributedPrimaryKeyValues(
                ec.getMetaDataManager(), storeMgr, clr);

            boolean inserted = false;
            if (ownerFieldNumber >= 0)
            {
                // Field mapping : is this field of the related object present in the datastore?
                inserted = storeMgr.isObjectInserted(valueSM, ownerFieldNumber);
            }
            else if (mmd == null)
            {
                // Identity mapping : is the object inserted far enough to be considered of this mapping type?
                inserted = storeMgr.isObjectInserted(valueSM, type);
            }

            if (valueSM != null)
            {
                if (ec.getApiAdapter().isDetached(value) && valueSM.getReferencedPC() != null && ownerSM != null && mmd != null)
View Full Code Here

     * @return The Persistence Capable object
     */
    public Object getObject(ExecutionContext ec, final Object rs, int[] param)
    {
        // Check for null FK
        MappedStoreManager storeMgr = (MappedStoreManager)ec.getStoreManager();
        if (storeMgr.getResultValueAtPosition(rs, this, param[0]) == null)
        {
            // if the first param is null, then the field is null
            return null;
        }

View Full Code Here

    {
        // SingleFieldIdentity
        int paramNumber = param[0];
        try
        {
            MappedStoreManager storeMgr = (MappedStoreManager)ec.getStoreManager();
            Object idObj = storeMgr.getResultValueAtPosition(rs, this, paramNumber);
            if (idObj == null)
            {
                throw new NucleusException(LOCALISER.msg("041039")).setFatal();
            }
            else
View Full Code Here

TOP

Related Classes of org.datanucleus.store.mapped.MappedStoreManager

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.