Package org.datanucleus.store.connection

Examples of org.datanucleus.store.connection.ManagedConnection


        {
            // Update/Delete statement (INSERT/UPDATE/DELETE/MERGE)
            try
            {
                RDBMSStoreManager storeMgr = (RDBMSStoreManager)ec.getStoreManager();
                ManagedConnection mconn = storeMgr.getConnection(ec);
                SQLController sqlControl = storeMgr.getSQLController();

                try
                {
                    PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, compiledSQL, false);
                    try
                    {
                        // Set the values of any parameters
                        for (int i=0;i<parameters.size();i++)
                        {
                            Object obj = parameters.get(Integer.valueOf(i+1));
                            ps.setObject((i+1), obj);
                        }

                        // Execute the update statement
                        int[] rcs = sqlControl.executeStatementUpdate(mconn, compiledSQL, ps, true);
                        return Long.valueOf(rcs[0]); // Return a single Long with the number of records updated
                    }
                    finally
                    {
                        sqlControl.closeStatement(mconn, ps);
                    }
                }
                finally
                {
                    mconn.release();
                }
            }
            catch (SQLException e)
            {
                throw new NucleusDataStoreException(LOCALISER.msg("059025", compiledSQL), e);
            }
        }
        else
        {
            // Query statement (SELECT, stored-procedure)
            QueryResult qr = null;
            try
            {
                RDBMSStoreManager storeMgr = (RDBMSStoreManager)ec.getStoreManager();
                ManagedConnection mconn = storeMgr.getConnection(ec);
                SQLController sqlControl = storeMgr.getSQLController();

                try
                {
                    PreparedStatement ps = RDBMSQueryUtils.getPreparedStatementForQuery(mconn, compiledSQL, this);
                    try
                    {
                        // Set the values of any parameters
                        for (int i=0;i<parameters.size();i++)
                        {
                            Object obj = parameters.get(Integer.valueOf(i+1));
                            ps.setObject((i+1), obj);
                        }

                        // Apply any user-specified constraints over timeouts and ResultSet
                        RDBMSQueryUtils.prepareStatementForExecution(ps, this, false);

                        ResultSet rs = sqlControl.executeStatementQuery(mconn, compiledSQL, ps);
                        try
                        {
                            // Generate a ResultObjectFactory
                            ResultObjectFactory rof = null;
                            if (resultMetaData != null)
                            {
                                // Each row of the ResultSet is defined by MetaData
                                rof = new ResultMetaDataROF(resultMetaData);
                            }
                            else if (resultClass != null || candidateClass == null)
                            {
                                // Each row of the ResultSet is either an instance of resultClass, or Object[]
                                rof = getResultObjectFactoryForNoCandidateClass(rs, resultClass);
                            }
                            else
                            {
                                // Each row of the ResultSet is an instance of the candidate class
                                rof = getResultObjectFactoryForCandidateClass(rs);
                            }

                            // Return the associated type of results depending on whether scrollable or not
                            String resultSetType = RDBMSQueryUtils.getResultSetTypeForQuery(this);
                            if (resultSetType.equals("scroll-insensitive") ||
                                resultSetType.equals("scroll-sensitive"))
                            {
                                qr = new ScrollableQueryResult(this, rof, rs, null);
                            }
                            else
                            {
                                qr = new ForwardQueryResult(this, rof, rs, null);
                            }

                            final QueryResult qr1 = qr;
                            final ManagedConnection mconn1 = mconn;
                            mconn.addListener(new ManagedConnectionResourceListener()
                            {
                                public void transactionFlushed(){}
                                public void transactionPreClose(){}
                                {
                                    qr1.disconnect();                       
                                }
                                public void managedConnectionPreClose(){}
                                public void managedConnectionPostClose(){}
                                public void resourcePostClose()
                                {
                                    mconn1.removeListener(this);
                                }
                            });                           
                        }
                        finally
                        {
View Full Code Here


                    NucleusLogger.PERSISTENCE.warn("FKSetStore.updateElementFK : " +
                        "need to set table in statement but dont know table where to store " +
                        elementInfo[0].getClassName());
                }
            }
            ManagedConnection mconn = getStoreMgr().getConnection(ec);
            SQLController sqlControl = getStoreMgr().getSQLController();
            try
            {
                PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, stmt, false);
                try
                {
                    int jdbcPosition = 1;
                    BackingStoreHelper.populateOwnerInStatement(ownerSM, ec, ps, jdbcPosition, this);
                    sqlControl.executeStatementUpdate(mconn, stmt, ps, true);
                }
                finally
                {
                    sqlControl.closeStatement(mconn, ps);
                }
            }
            finally
            {
                mconn.release();
            }
        }
        catch (SQLException e)
        {
            throw new NucleusDataStoreException(LOCALISER.msg("056013",stmt),e);
View Full Code Here

        boolean retval;
        ExecutionContext ec = sm.getExecutionContext();
        String stmt = getUpdateFkStmt();
        try
        {
            ManagedConnection mconn = getStoreMgr().getConnection(ec);
            SQLController sqlControl = getStoreMgr().getSQLController();
            try
            {
                int jdbcPosition = 1;
                if (elementInfo.length > 1)
                {
                    DatastoreClass table = getStoreMgr().getDatastoreClass(element.getClass().getName(), clr);
                    if (table != null)
                    {
                        stmt = stmt.replace("<TABLE NAME>", table.toString());
                    }
                    else
                    {
                        NucleusLogger.PERSISTENCE.warn("FKSetStore.updateElementFK : need to set table in statement but dont know table where to store " + element);
                    }
                }
                PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, stmt, false);
                try
                {
                    if (owner == null)
                    {
                        if (ownerMemberMetaData != null)
                        {
                            ownerMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, ownerMapping),
                                null, sm, ownerMemberMetaData.getAbsoluteFieldNumber());
                        }
                        else
                        {
                            ownerMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, ownerMapping),
                                null);
                        }
                    }
                    else
                    {
                        if (ownerMemberMetaData != null)
                        {
                            ownerMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, ownerMapping),
                                sm.getObject(), sm, ownerMemberMetaData.getAbsoluteFieldNumber());
                        }
                        else
                        {
                            ownerMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, ownerMapping),
                                sm.getObject());
                        }
                    }
                    jdbcPosition += ownerMapping.getNumberOfDatastoreMappings();

                    if (relationDiscriminatorMapping != null)
                    {
                        jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
                    }
                    elementMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, elementMapping), element);
                    jdbcPosition += elementMapping.getNumberOfDatastoreMappings();

                    sqlControl.executeStatementUpdate(mconn, stmt, ps, true);
                    retval = true;
                }
                finally
                {
                    sqlControl.closeStatement(mconn, ps);
                }
            }
            finally
            {
                mconn.release();
            }
        }
        catch (SQLException e)
        {
            throw new NucleusDataStoreException(LOCALISER.msg("056027", stmt), e);
View Full Code Here

        Transaction tx = ec.getTransaction();
        String stmt = (tx.lockReadObjects() ? iteratorStmtLocked : iteratorStmtUnlocked);
        try
        {
            ManagedConnection mconn = storeMgr.getConnection(ec);
            SQLController sqlControl = ((RDBMSStoreManager)storeMgr).getSQLController();
            try
            {
                // Create the statement and set the owner
                PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
                StatementMappingIndex ownerIdx = iteratorMappingParams.getMappingForParameter("owner");
                int numParams = ownerIdx.getNumberOfParameterOccurrences();
                for (int paramInstance=0;paramInstance<numParams;paramInstance++)
                {
                    ownerIdx.getMapping().setObject(ec, ps,
                        ownerIdx.getParameterPositionsForOccurrence(paramInstance), ownerSM.getObject());
                }

                try
                {
                    ResultSet rs = sqlControl.executeStatementQuery(mconn, stmt, ps);
                    try
                    {
                        ResultObjectFactory rof = null;
                        if (elementsAreEmbedded || elementsAreSerialised)
                        {
                            throw new NucleusException("Cannot have FK set with non-persistent objects");
                        }
                        else
                        {
                            rof = storeMgr.newResultObjectFactory(emd, iteratorMappingDef, false, null,
                                clr.classForName(elementType));
                        }

                        return new RDBMSSetStoreIterator(ownerSM, rs, rof, this);
                    }
                    finally
                    {
                        rs.close();
                    }
                }
                finally
                {
                    sqlControl.closeStatement(mconn, ps);
                }
            }
            finally
            {
                mconn.release();
            }
        }
        catch (SQLException e)
        {
            throw new NucleusDataStoreException(LOCALISER.msg("056006", stmt),e);
View Full Code Here

        expressionFactory = new SQLExpressionFactory(this);

        // Retrieve the Database Adapter for this datastore
        try
        {
            ManagedConnection mc = getConnection(-1);
            Connection conn = (Connection)mc.getConnection();
            if (conn == null)
            {
                //somehow we haven't got an exception from the JDBC driver
                //to troubleshoot the user should telnet to ip/port of database and check if he can open a connection
                //this may be due to security / firewall things.
                throw new NucleusDataStoreException(LOCALISER_RDBMS.msg("050007"));
            }

            try
            {
                dba = RDBMSAdapterFactory.getInstance().getDatastoreAdapter(clr, conn,
                    getStringProperty("datanucleus.rdbms.datastoreAdapterClassName"),
                    ctx.getPluginManager());
                dba.initialiseTypes(schemaHandler, mc);
                dba.removeUnsupportedMappings(schemaHandler, mc);

                // User specified default catalog/schema name - check for validity, and store
                if (hasPropertyNotNull("datanucleus.mapping.Catalog"))
                {
                    if (!((RDBMSAdapter)dba).supportsOption(RDBMSAdapter.CATALOGS_IN_TABLE_DEFINITIONS))
                    {
                        NucleusLogger.DATASTORE.warn(LOCALISER_RDBMS.msg("050002",
                            getStringProperty("datanucleus.mapping.Catalog")));
                    }
                    else
                    {
                        catalogName = getStringProperty("datanucleus.mapping.Catalog");
                    }
                }
                if (hasPropertyNotNull("datanucleus.mapping.Schema"))
                {
                    if (!((RDBMSAdapter)dba).supportsOption(DatastoreAdapter.SCHEMAS_IN_TABLE_DEFINITIONS))
                    {
                        NucleusLogger.DATASTORE.warn(LOCALISER_RDBMS.msg("050002",
                            getStringProperty("datanucleus.mapping.Schema")));
                    }
                    else
                    {
                        schemaName = getStringProperty("datanucleus.mapping.Schema");
                    }
                }

                // Create an identifier factory - needs the database adapter to exist first
                initialiseIdentifierFactory(ctx);

                // Now that we have the identifier factory, make sure any user-provided names were valid!
                if (schemaName != null)
                {
                    String validSchemaName = identifierFactory.getIdentifierInAdapterCase(schemaName);
                    if (!validSchemaName.equals(schemaName))
                    {
                        NucleusLogger.DATASTORE_SCHEMA.warn(LOCALISER_RDBMS.msg("020192", "schema", schemaName, validSchemaName));
                        schemaName = validSchemaName;
                    }
                }
                if (catalogName != null)
                {
                    String validCatalogName = identifierFactory.getIdentifierInAdapterCase(catalogName);
                    if (!validCatalogName.equals(catalogName))
                    {
                        NucleusLogger.DATASTORE_SCHEMA.warn(LOCALISER_RDBMS.msg("020192", "catalog", catalogName, validCatalogName));
                        catalogName = validCatalogName;
                    }
                }

                // Create the SQL controller
                sqlController = new SQLController(((RDBMSAdapter)dba).supportsOption(RDBMSAdapter.STATEMENT_BATCHING),
                    getIntProperty("datanucleus.rdbms.statementBatchLimit"),
                    getIntProperty("datanucleus.datastoreReadTimeout"),
                    getBooleanProperty("datanucleus.rdbms.sqlParamValuesInBrackets"));

                // TODO These ought to be stored with the StoreManager, not the NucleusContext
                // Initialise any properties controlling the adapter
                // Just use properties matching the pattern "datanucleus.rdbms.adapter.*"
                Map<String, Object> dbaProps = new HashMap();
                Map<String, Object> omfProps = ctx.getPersistenceConfiguration().getPersistenceProperties();
                Iterator<Map.Entry<String, Object>> propIter = omfProps.entrySet().iterator();
                while (propIter.hasNext())
                {
                    Map.Entry<String, Object> entry = propIter.next();
                    String prop = entry.getKey();
                    if (prop.startsWith("datanucleus.rdbms.adapter."))
                    {
                        dbaProps.put(prop, entry.getValue());
                    }
                }
                if (dbaProps.size() > 0)
                {
                    dba.setProperties(dbaProps);
                }

                // Initialise the Schema
                initialiseSchema(conn, clr);

                // Log the configuration of the RDBMS
                logConfiguration();
            }
            finally
            {
                mc.close();
            }
        }
        catch (NucleusException ne)
        {
            NucleusLogger.DATASTORE_SCHEMA.error(LOCALISER_RDBMS.msg("050004"), ne);
View Full Code Here

     * @param ec execution context
     * @return The NucleusConnection
     */
    public NucleusConnection getNucleusConnection(final ExecutionContext ec)
    {
        final ManagedConnection mc;
        final boolean enlisted;
        if (!ec.getTransaction().isActive())
        {
            // no active transaction so dont enlist
            enlisted = false;
        }
        else
        {
            enlisted = true;
        }
        ConnectionFactory cf = null;
        if (enlisted)
        {
            cf = connectionMgr.lookupConnectionFactory(txConnectionFactoryName);
        }
        else
        {
            cf = connectionMgr.lookupConnectionFactory(nontxConnectionFactoryName);
        }
        mc = cf.getConnection(enlisted ? ec : null, ec.getTransaction(), null); // Will throw exception if already locked

        // Lock the connection now that it is in use by the user
        mc.lock();

        Runnable closeRunnable = new Runnable()
        {
            public void run()
            {
                // Unlock the connection now that the user has finished with it
                mc.unlock();
                if (!enlisted)
                {
                    // Close the (unenlisted) connection (committing its statements)
                    try
                    {
                        ((Connection)mc.getConnection()).close();
                    }
                    catch (SQLException sqle)
                    {
                        throw new NucleusDataStoreException(sqle.getMessage());
                    }
                }
            }
        };
        NucleusConnection nc = new NucleusConnectionImpl(mc.getConnection(), closeRunnable);

        // Return own implementation of JDOConnection since we need to implement JDBC Connection too as per the spec
        return new JDOConnectionImpl(nc);
    }
View Full Code Here

    public Date getDatastoreDate()
    {
        Date serverDate = null;

        String dateStmt = ((RDBMSAdapter)dba).getDatastoreDateStatement();
        ManagedConnection mconn = null;
        try
        {
            mconn = getConnection(UserTransaction.TRANSACTION_NONE);

            PreparedStatement ps = null;
            ResultSet rs = null;
            try
            {
                ps = getSQLController().getStatementForQuery(mconn, dateStmt);
                rs = getSQLController().executeStatementQuery(mconn, dateStmt, ps);
                if (rs.next())
                {
                    // Retrieve the timestamp for the server date/time using the server TimeZone from OMF
                    // Assume that the dateStmt returns 1 column and is Timestamp
                    Timestamp time = rs.getTimestamp(1, getCalendarForDateTimezone());
                    serverDate = new Date(time.getTime());
                }
                else
                {
                    return null;
                }
            }
            catch (SQLException sqle)
            {
                String msg = LOCALISER_RDBMS.msg("050052", sqle.getMessage());
                NucleusLogger.DATASTORE.warn(msg, sqle);
                throw new NucleusUserException(msg, sqle).setFatal();
            }
            finally
            {
                if (rs != null)
                {
                    rs.close();
                }
                if (ps != null)
                {
                    getSQLController().closeStatement(mconn, ps);
                }
            }
        }
        catch (SQLException sqle)
        {
            String msg = LOCALISER_RDBMS.msg("050052", sqle.getMessage());
            NucleusLogger.DATASTORE.warn(msg, sqle);
            throw new NucleusException(msg, sqle).setFatal();
        }
        finally
        {
            mconn.close();
        }

        return serverDate;
    }
View Full Code Here

        {
            ps.println(dba.toString());
            ps.println();
            ps.println("TABLES");

            ManagedConnection mc = getConnection(-1);
            try
            {
                Connection conn = (Connection)mc.getConnection();
                RDBMSSchemaInfo schemaInfo = (RDBMSSchemaInfo)schemaHandler.getSchemaData(
                    conn, "tables", new Object[] {this.catalogName, this.schemaName});
                if (schemaInfo != null)
                {
                    Iterator tableIter = schemaInfo.getChildren().values().iterator();
                    while (tableIter.hasNext())
                    {
                        // Print out the table information
                        RDBMSTableInfo tableInfo = (RDBMSTableInfo)tableIter.next();
                        ps.println(tableInfo);

                        Iterator columnIter = tableInfo.getChildren().iterator();
                        while (columnIter.hasNext())
                        {
                            // Print out the column information
                            RDBMSColumnInfo colInfo = (RDBMSColumnInfo)columnIter.next();
                            ps.println(colInfo);
                        }
                    }
                }
            }
            finally
            {
                if (mc != null)
                {
                    mc.close();
                }
            }
            ps.println("");
        }
    }
View Full Code Here

            nextValColName = md.getValueForExtension("sequence-nextval-column-name");
        }

        if (!seqTablesGenerated.contains(tableName))
        {
            ManagedConnection mconn = getConnection(UserTransaction.TRANSACTION_NONE);
            Connection conn = (Connection) mconn.getConnection();
            try
            {
                DatastoreIdentifier tableIdentifier = identifierFactory.newDatastoreContainerIdentifier(tableName);
                if (catName != null)
                {
                    tableIdentifier.setCatalogName(catName);
                }
                if (schName != null)
                {
                    tableIdentifier.setSchemaName(schName);
                }
                SequenceTable seqTable = new SequenceTable(tableIdentifier, this, seqColName, nextValColName);
                seqTable.initialize(clr);
                seqTable.exists(conn, true);
            }
            catch (Exception e)
            {
            }
            finally
            {
                mconn.close();
            }
            seqTablesGenerated.add(tableName);
        }
    }
View Full Code Here

                }
            }
            else
            {
                PreparedStatement ps = null;
                ManagedConnection mconn = getConnection(UserTransaction.TRANSACTION_NONE);
                try
                {
                    ps = sqlController.getStatementForUpdate(mconn, stmt, false);
                    sqlController.executeStatementUpdate(mconn, stmt, ps, true);
                }
                catch (SQLException e)
                {
                }
                finally
                {
                    try
                    {
                        if (ps != null)
                        {
                            sqlController.closeStatement(mconn, ps);
                        }
                    }
                    catch (SQLException e)
                    {
                    }
                    mconn.close();
                }
            }
            sequencesGenerated.add(seqName);
        }
    }
View Full Code Here

TOP

Related Classes of org.datanucleus.store.connection.ManagedConnection

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.