Search in sources :

Example 16 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project datanucleus-rdbms by datanucleus.

the class SequenceGenerator method reserveBlock.

/**
 * Reserve a block of ids.
 * @param size Block size
 * @return The reserved block
 */
protected synchronized ValueGenerationBlock<Long> reserveBlock(long size) {
    if (size < 1) {
        return null;
    }
    PreparedStatement ps = null;
    ResultSet rs = null;
    List oid = new ArrayList();
    RDBMSStoreManager srm = (RDBMSStoreManager) storeMgr;
    SQLController sqlControl = srm.getSQLController();
    try {
        // Get next available id
        DatastoreAdapter dba = srm.getDatastoreAdapter();
        String stmt = dba.getSequenceNextStmt(sequenceName);
        ps = sqlControl.getStatementForQuery(connection, stmt);
        rs = sqlControl.executeStatementQuery(null, connection, stmt, ps);
        Long nextId = Long.valueOf(0);
        if (rs.next()) {
            nextId = Long.valueOf(rs.getLong(1));
            oid.add(nextId);
        }
        for (int i = 1; i < size; i++) {
            // size must match key-increment-by otherwise it will
            // cause duplicates keys
            nextId = Long.valueOf(nextId.longValue() + 1);
            oid.add(nextId);
        }
        if (NucleusLogger.VALUEGENERATION.isDebugEnabled()) {
            NucleusLogger.VALUEGENERATION.debug(Localiser.msg("040004", "" + size));
        }
        return new ValueGenerationBlock<>(oid);
    } catch (SQLException e) {
        throw new ValueGenerationException(Localiser.msg("061001", e.getMessage()), e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                sqlControl.closeStatement(connection, ps);
            }
        } catch (SQLException e) {
        // non-recoverable error
        }
    }
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) ValueGenerationBlock(org.datanucleus.store.valuegenerator.ValueGenerationBlock) PreparedStatement(java.sql.PreparedStatement) ValueGenerationException(org.datanucleus.store.valuegenerator.ValueGenerationException) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) SQLController(org.datanucleus.store.rdbms.SQLController) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter)

Example 17 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project datanucleus-rdbms by datanucleus.

the class SequenceGenerator method createRepository.

/**
 * Method to create the sequence.
 * @return Whether it was created successfully.
 */
protected boolean createRepository() {
    PreparedStatement ps = null;
    RDBMSStoreManager srm = (RDBMSStoreManager) storeMgr;
    DatastoreAdapter dba = srm.getDatastoreAdapter();
    SQLController sqlControl = srm.getSQLController();
    if (!srm.getSchemaHandler().isAutoCreateTables()) {
        throw new NucleusUserException(Localiser.msg("040010", sequenceName));
    }
    Integer min = properties.containsKey(ValueGenerator.PROPERTY_KEY_MIN_VALUE) ? Integer.valueOf(properties.getProperty(ValueGenerator.PROPERTY_KEY_MIN_VALUE)) : null;
    Integer max = properties.containsKey(ValueGenerator.PROPERTY_KEY_MAX_VALUE) ? Integer.valueOf(properties.getProperty(ValueGenerator.PROPERTY_KEY_MAX_VALUE)) : null;
    Integer start = properties.containsKey(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE) ? Integer.valueOf(properties.getProperty(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE)) : null;
    Integer incr = properties.containsKey(ValueGenerator.PROPERTY_KEY_CACHE_SIZE) ? Integer.valueOf(properties.getProperty(ValueGenerator.PROPERTY_KEY_CACHE_SIZE)) : null;
    Integer cacheSize = properties.containsKey(ValueGenerator.PROPERTY_KEY_DATABASE_CACHE_SIZE) ? Integer.valueOf(properties.getProperty(ValueGenerator.PROPERTY_KEY_DATABASE_CACHE_SIZE)) : null;
    String stmt = dba.getSequenceCreateStmt(sequenceName, min, max, start, incr, cacheSize);
    try {
        ps = sqlControl.getStatementForUpdate(connection, stmt, false);
        sqlControl.executeStatementUpdate(null, connection, stmt, ps, true);
    } catch (SQLException e) {
        NucleusLogger.DATASTORE.error(e);
        throw new ValueGenerationException(Localiser.msg("061000", e.getMessage()) + stmt);
    } finally {
        try {
            if (ps != null) {
                sqlControl.closeStatement(connection, ps);
            }
        } catch (SQLException e) {
        // non-recoverable error
        }
    }
    return true;
}
Also used : SQLException(java.sql.SQLException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) PreparedStatement(java.sql.PreparedStatement) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) ValueGenerationException(org.datanucleus.store.valuegenerator.ValueGenerationException) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 18 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter 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 19 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project datanucleus-rdbms by datanucleus.

the class DatastoreAdapterFactory method getNewDatastoreAdapter.

/**
 * Accessor for the adapter for a specified datastore product.
 * @param clr ClassLoader resolver for resolving the adapter class
 * @param metadata Database MetaData for the RDBMS
 * @param adapterClassName Name of the class of the database adapter (null implies use autodetect)
 * @param pluginMgr the Plug-in manager
 * @return Instance of the database adapter
 */
protected DatastoreAdapter getNewDatastoreAdapter(ClassLoaderResolver clr, DatabaseMetaData metadata, String adapterClassName, PluginManager pluginMgr) {
    if (metadata == null) {
        return null;
    }
    String productName = null;
    if (adapterClassName == null) {
        // No adapter specified, so use "autodetection" based on the metadata to find the most suitable
        try {
            productName = metadata.getDatabaseProductName();
            if (productName == null) {
                NucleusLogger.DATASTORE.error(Localiser.msg("051024"));
                return null;
            }
        } catch (SQLException sqe) {
            NucleusLogger.DATASTORE.error(Localiser.msg("051025", sqe));
            return null;
        }
    }
    // Instantiate the adapter class
    final Object adapter_obj;
    try {
        Class adapterClass = getAdapterClass(pluginMgr, adapterClassName, productName, clr);
        if (adapterClass == null) {
            return null;
        }
        final Object[] ctr_args = new Object[] { metadata };
        final Class[] ctr_args_classes = new Class[] { DatabaseMetaData.class };
        // Create an instance of the datastore adapter
        final Constructor ctr = adapterClass.getConstructor(ctr_args_classes);
        try {
            adapter_obj = ctr.newInstance(ctr_args);
        } catch (InvocationTargetException ite) {
            if (ite.getTargetException() != null && ite.getTargetException() instanceof NucleusDataStoreException) {
                throw (NucleusDataStoreException) ite.getTargetException();
            }
            return null;
        } catch (Exception e) {
            NucleusLogger.DATASTORE.error(Localiser.msg("051026", adapterClassName, e));
            return null;
        }
    } catch (ClassNotResolvedException ex) {
        NucleusLogger.DATASTORE.error(Localiser.msg("051026", adapterClassName, ex));
        return null;
    } catch (NoSuchMethodException nsme) {
        NucleusLogger.DATASTORE.error(Localiser.msg("051026", adapterClassName, nsme));
        return null;
    }
    return (DatastoreAdapter) adapter_obj;
}
Also used : SQLException(java.sql.SQLException) Constructor(java.lang.reflect.Constructor) DatabaseMetaData(java.sql.DatabaseMetaData) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) InvocationTargetException(java.lang.reflect.InvocationTargetException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter)

Example 20 with DatastoreAdapter

use of org.datanucleus.store.rdbms.adapter.DatastoreAdapter in project datanucleus-rdbms by datanucleus.

the class DatastoreAdapterFactory method getDatastoreAdapter.

/**
 * Accessor for an adapter, given a Connection to the datastore.
 * @param clr ClassLoader resolver for resolving the adapter class
 * @param conn The Connection
 * @param adapterClassName Name of the class of the database adapter to use
 * @param pluginMgr the Plug-in manager
 * @return The database adapter for this connection.
 * @throws SQLException Thrown if a DB error occurs.
 */
public DatastoreAdapter getDatastoreAdapter(ClassLoaderResolver clr, Connection conn, String adapterClassName, PluginManager pluginMgr) throws SQLException {
    DatastoreAdapter adapter = null;
    DatabaseMetaData metadata = conn.getMetaData();
    // Get a new adapter
    adapter = getNewDatastoreAdapter(clr, metadata, adapterClassName, pluginMgr);
    if (adapter == null) {
        // Nothing suitable found so warn the user and continue with the generic adapter
        NucleusLogger.DATASTORE.warn(Localiser.msg("051000"));
        adapter = new BaseDatastoreAdapter(metadata);
    }
    return adapter;
}
Also used : DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) DatabaseMetaData(java.sql.DatabaseMetaData)

Aggregations

DatastoreAdapter (org.datanucleus.store.rdbms.adapter.DatastoreAdapter)46 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)24 SQLException (java.sql.SQLException)17 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)10 ResultSet (java.sql.ResultSet)8 List (java.util.List)8 Connection (java.sql.Connection)7 Statement (java.sql.Statement)7 EntityTransaction (javax.persistence.EntityTransaction)7 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)7 Person (org.datanucleus.samples.annotations.models.company.Person)7 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)7 PreparedStatement (java.sql.PreparedStatement)6 ArrayList (java.util.ArrayList)6 SQLController (org.datanucleus.store.rdbms.SQLController)6 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)6 StoredProcedureQuery (javax.persistence.StoredProcedureQuery)5 JPAEntityManager (org.datanucleus.api.jpa.JPAEntityManager)5 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)5 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)5