Search in sources :

Example 41 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection in project datanucleus-rdbms by datanucleus.

the class MaxGenerator method reserveBlock.

/**
 * Method to reserve a block of identities.
 * Note : Only allocates a single id always.
 * @param size The block size
 * @return The reserved block
 */
public ValueGenerationBlock reserveBlock(long size) {
    try {
        // search an Id in the database
        ManagedConnection mconn = connectionProvider.retrieveConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        SQLController sqlControl = ((RDBMSStoreManager) storeMgr).getSQLController();
        try {
            String stmt = getStatement();
            ps = sqlControl.getStatementForUpdate(mconn, stmt, false);
            rs = sqlControl.executeStatementQuery(null, mconn, stmt, ps);
            if (!rs.next()) {
                return new ValueGenerationBlock(new Object[] { Long.valueOf(1) });
            }
            return new ValueGenerationBlock(new Object[] { Long.valueOf(rs.getLong(1) + 1) });
        } catch (SQLException e) {
            NucleusLogger.VALUEGENERATION.warn("Exception thrown getting next value for MaxGenerator", e);
            throw new ValueGenerationException("Exception thrown getting next value for MaxGenerator", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    sqlControl.closeStatement(mconn, ps);
                }
            } catch (SQLException e) {
            // no recoverable error
            }
        }
    } finally {
        connectionProvider.releaseConnection();
    }
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) ValueGenerationBlock(org.datanucleus.store.valuegenerator.ValueGenerationBlock) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) PreparedStatement(java.sql.PreparedStatement) ValueGenerationException(org.datanucleus.store.valuegenerator.ValueGenerationException) SQLController(org.datanucleus.store.rdbms.SQLController) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager)

Example 42 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection in project datanucleus-rdbms by datanucleus.

the class RDBMSStoreManager method addSequenceTableForMetaData.

protected void addSequenceTableForMetaData(MetaData md, ClassLoaderResolver clr, Set<String> seqTablesGenerated) {
    String catName = null;
    String schName = null;
    String tableName = TableGenerator.DEFAULT_TABLE_NAME;
    String seqColName = TableGenerator.DEFAULT_SEQUENCE_COLUMN_NAME;
    String nextValColName = TableGenerator.DEFAULT_NEXTVALUE_COLUMN_NAME;
    if (md.hasExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_CATALOG)) {
        catName = md.getValueForExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_CATALOG);
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_SCHEMA)) {
        schName = md.getValueForExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_SCHEMA);
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_TABLE)) {
        tableName = md.getValueForExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_TABLE);
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_NAME_COLUMN)) {
        seqColName = md.getValueForExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_NAME_COLUMN);
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_NEXTVAL_COLUMN)) {
        nextValColName = md.getValueForExtension(ValueGenerator.PROPERTY_SEQUENCETABLE_NEXTVAL_COLUMN);
    }
    if (!seqTablesGenerated.contains(tableName)) {
        ManagedConnection mconn = connectionMgr.getConnection(TransactionIsolation.NONE);
        Connection conn = (Connection) mconn.getConnection();
        try {
            DatastoreIdentifier tableIdentifier = identifierFactory.newTableIdentifier(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.release();
        }
        seqTablesGenerated.add(tableName);
    }
}
Also used : DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) Connection(java.sql.Connection) NucleusConnection(org.datanucleus.store.NucleusConnection) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) SequenceTable(org.datanucleus.store.rdbms.valuegenerator.SequenceTable) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) MacroString(org.datanucleus.util.MacroString) SQLException(java.sql.SQLException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) IOException(java.io.IOException) NucleusException(org.datanucleus.exceptions.NucleusException) UnsupportedDataTypeException(org.datanucleus.store.rdbms.exceptions.UnsupportedDataTypeException) NoTableManagedException(org.datanucleus.store.rdbms.exceptions.NoTableManagedException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) IncompatibleFieldTypeException(org.datanucleus.store.types.IncompatibleFieldTypeException)

Example 43 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection in project datanucleus-rdbms by datanucleus.

the class RDBMSStoreManager method printInformation.

/**
 * Method to output particular information owned by this datastore.
 * Supports "DATASTORE" and "SCHEMA" categories.
 * @param category Category of information
 * @param ps PrintStream
 * @throws Exception Thrown if an error occurs in the output process
 */
public void printInformation(String category, PrintStream ps) throws Exception {
    DatastoreAdapter dba = getDatastoreAdapter();
    super.printInformation(category, ps);
    if (category.equalsIgnoreCase("DATASTORE")) {
        ps.println(dba.toString());
        ps.println();
        ps.println("Database TypeInfo");
        RDBMSTypesInfo typesInfo = (RDBMSTypesInfo) schemaHandler.getSchemaData(null, "types", null);
        if (typesInfo != null) {
            Iterator iter = typesInfo.getChildren().keySet().iterator();
            while (iter.hasNext()) {
                String jdbcTypeStr = (String) iter.next();
                short jdbcTypeNumber = 0;
                try {
                    jdbcTypeNumber = Short.parseShort(jdbcTypeStr);
                } catch (NumberFormatException nfe) {
                }
                JDBCTypeInfo jdbcType = (JDBCTypeInfo) typesInfo.getChild(jdbcTypeStr);
                Collection<String> sqlTypeNames = jdbcType.getChildren().keySet();
                StringBuilder sqlTypesName = new StringBuilder();
                String defaultSqlTypeName = null;
                for (String sqlTypeName : sqlTypeNames) {
                    if (!sqlTypeName.equals("DEFAULT")) {
                        if (sqlTypesName.length() > 0) {
                            sqlTypesName.append(',');
                        }
                        sqlTypesName.append(sqlTypeName);
                    } else {
                        defaultSqlTypeName = ((SQLTypeInfo) jdbcType.getChild(sqlTypeName)).getTypeName();
                    }
                }
                // SQL type names for JDBC type
                String typeStr = "JDBC Type=" + dba.getNameForJDBCType(jdbcTypeNumber) + " sqlTypes=" + sqlTypesName + (defaultSqlTypeName != null ? (" (default=" + defaultSqlTypeName + ")") : "");
                ps.println(typeStr);
                for (String sqlTypeName : sqlTypeNames) {
                    // SQL type details
                    if (!sqlTypeName.equals("DEFAULT")) {
                        SQLTypeInfo sqlType = (SQLTypeInfo) jdbcType.getChild(sqlTypeName);
                        ps.println(sqlType.toString("    "));
                    }
                }
            }
        }
        ps.println("");
        // Print out the keywords info
        ps.println("Database Keywords");
        Iterator reservedWordsIter = dba.iteratorReservedWords();
        while (reservedWordsIter.hasNext()) {
            Object words = reservedWordsIter.next();
            ps.println(words);
        }
        ps.println("");
    } else if (category.equalsIgnoreCase("SCHEMA")) {
        ps.println(dba.toString());
        ps.println();
        ps.println("TABLES");
        ManagedConnection mc = connectionMgr.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<StoreSchemaData> 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.release();
            }
        }
        ps.println("");
    }
}
Also used : RDBMSColumnInfo(org.datanucleus.store.rdbms.schema.RDBMSColumnInfo) RDBMSTableInfo(org.datanucleus.store.rdbms.schema.RDBMSTableInfo) Connection(java.sql.Connection) NucleusConnection(org.datanucleus.store.NucleusConnection) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) MacroString(org.datanucleus.util.MacroString) SQLTypeInfo(org.datanucleus.store.rdbms.schema.SQLTypeInfo) JDBCTypeInfo(org.datanucleus.store.rdbms.schema.JDBCTypeInfo) ListIterator(java.util.ListIterator) Iterator(java.util.Iterator) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) RDBMSTypesInfo(org.datanucleus.store.rdbms.schema.RDBMSTypesInfo) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) RDBMSSchemaInfo(org.datanucleus.store.rdbms.schema.RDBMSSchemaInfo)

Example 44 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection in project datanucleus-rdbms by datanucleus.

the class RDBMSStoreManager method addSequenceForMetaData.

protected void addSequenceForMetaData(MetaData md, String seq, ClassLoaderResolver clr, Set<String> sequencesGenerated, FileWriter ddlWriter) {
    String seqName = seq;
    Integer min = null;
    Integer max = null;
    Integer start = null;
    Integer increment = null;
    Integer cacheSize = null;
    SequenceMetaData seqmd = getMetaDataManager().getMetaDataForSequence(clr, seq);
    if (seqmd != null) {
        seqName = seqmd.getDatastoreSequence();
        if (seqmd.getAllocationSize() > 0) {
            increment = Integer.valueOf(seqmd.getAllocationSize());
        }
        if (seqmd.getInitialValue() >= 0) {
            start = Integer.valueOf(seqmd.getInitialValue());
        }
        md = seqmd;
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_MIN_VALUE)) {
        min = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_MIN_VALUE));
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_MAX_VALUE)) {
        max = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_MAX_VALUE));
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_CACHE_SIZE)) {
        increment = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_CACHE_SIZE));
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE)) {
        start = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE));
    }
    if (md.hasExtension(ValueGenerator.PROPERTY_KEY_DATABASE_CACHE_SIZE)) {
        cacheSize = Integer.valueOf(md.getValueForExtension(ValueGenerator.PROPERTY_KEY_DATABASE_CACHE_SIZE));
    }
    if (!sequencesGenerated.contains(seqName)) {
        String stmt = getDatastoreAdapter().getSequenceCreateStmt(seqName, min, max, start, increment, cacheSize);
        if (ddlWriter != null) {
            try {
                ddlWriter.write(stmt + ";\n");
            } catch (IOException ioe) {
            }
        } else {
            PreparedStatement ps = null;
            ManagedConnection mconn = connectionMgr.getConnection(TransactionIsolation.NONE);
            try {
                ps = sqlController.getStatementForUpdate(mconn, stmt, false);
                sqlController.executeStatementUpdate(null, mconn, stmt, ps, true);
            } catch (SQLException e) {
            } finally {
                try {
                    if (ps != null) {
                        sqlController.closeStatement(mconn, ps);
                    }
                } catch (SQLException e) {
                }
                mconn.release();
            }
        }
        sequencesGenerated.add(seqName);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) MacroString(org.datanucleus.util.MacroString) IOException(java.io.IOException) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData)

Example 45 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection in project datanucleus-rdbms by datanucleus.

the class RDBMSStoreManager method executeScript.

/* (non-Javadoc)
     * @see org.datanucleus.store.schema.SchemaScriptAwareStoreManager#executeScript(java.lang.String)
     */
public void executeScript(String script) {
    script = StringUtils.replaceAll(script, "\n", " ");
    script = StringUtils.replaceAll(script, "\t", " ");
    ManagedConnection mc = connectionMgr.getConnection(-1);
    try {
        // Execute the script on this datastore
        // Note that we simply split the script at line delimiter (";")
        Connection conn = (Connection) mc.getConnection();
        Statement stmt = conn.createStatement();
        try {
            StringTokenizer tokeniser = new StringTokenizer(script, ";");
            while (tokeniser.hasMoreTokens()) {
                String token = tokeniser.nextToken().trim();
                if (!StringUtils.isWhitespace(token)) {
                    NucleusLogger.DATASTORE_NATIVE.debug("Executing script statement : " + token);
                    stmt.execute(token + ";");
                }
            }
        } finally {
            stmt.close();
        }
    } catch (SQLException e) {
        NucleusLogger.DATASTORE_NATIVE.error("Exception executing user script", e);
        throw new NucleusUserException("Exception executing user script. See nested exception for details", e);
    } finally {
        mc.release();
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) Connection(java.sql.Connection) NucleusConnection(org.datanucleus.store.NucleusConnection) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) MacroString(org.datanucleus.util.MacroString)

Aggregations

ManagedConnection (org.datanucleus.store.connection.ManagedConnection)157 SQLException (java.sql.SQLException)125 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)80 Connection (java.sql.Connection)75 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)74 PreparedStatement (java.sql.PreparedStatement)70 ExecutionContext (org.datanucleus.ExecutionContext)64 SQLController (org.datanucleus.store.rdbms.SQLController)63 HashSet (java.util.HashSet)62 DatabaseMetaData (java.sql.DatabaseMetaData)58 PersistenceManager (javax.jdo.PersistenceManager)46 Transaction (javax.jdo.Transaction)46 JDOFatalUserException (javax.jdo.JDOFatalUserException)45 JDOPersistenceManager (org.datanucleus.api.jdo.JDOPersistenceManager)45 ResultSet (java.sql.ResultSet)37 JDOFatalInternalException (javax.jdo.JDOFatalInternalException)24 JDODataStoreException (javax.jdo.JDODataStoreException)21 JDOUserException (javax.jdo.JDOUserException)21 MappedDatastoreException (org.datanucleus.store.rdbms.exceptions.MappedDatastoreException)21 EntityTransaction (javax.persistence.EntityTransaction)19