Search in sources :

Example 1 with InsertBatchQuery

use of org.apache.cayenne.query.InsertBatchQuery in project cayenne by apache.

the class FlushObserver method nextGeneratedRows.

/**
 * Processes generated keys.
 */
@Override
@SuppressWarnings("unchecked")
public void nextGeneratedRows(Query query, ResultIterator<?> keysIterator, List<ObjectId> idsToUpdate) {
    // read and close the iterator before doing anything else
    List<DataRow> keys;
    try {
        keys = (List<DataRow>) keysIterator.allRows();
    } finally {
        keysIterator.close();
    }
    if (!(query instanceof InsertBatchQuery)) {
        throw new CayenneRuntimeException("Generated keys only supported for InsertBatchQuery, instead got %s", query);
    }
    if (keys.size() != idsToUpdate.size()) {
        throw new CayenneRuntimeException("Mismatching number of generated PKs: expected %d, instead got %d", idsToUpdate.size(), keys.size());
    }
    for (int i = 0; i < keys.size(); i++) {
        DataRow key = keys.get(i);
        // empty key?
        if (key.size() == 0) {
            throw new CayenneRuntimeException("Empty key generated.");
        }
        ObjectId idToUpdate = idsToUpdate.get(i);
        if (idToUpdate == null || !idToUpdate.isTemporary()) {
            // why would this happen?
            return;
        }
        BatchQuery batch = (BatchQuery) query;
        for (DbAttribute attribute : batch.getDbEntity().getGeneratedAttributes()) {
            // DB DEFAULT values. Ignore those.
            if (attribute.isPrimaryKey()) {
                Object value = key.get(attribute.getName());
                // identity result sets, so a data row may contain garbage labels.
                if (value == null) {
                    value = key.values().iterator().next();
                }
                // Log the generated PK
                logger.logGeneratedKey(attribute, value);
                // I guess we should override any existing value,
                // as generated key is the latest thing that exists in the DB.
                idToUpdate.getReplacementIdMap().put(attribute.getName(), value);
                break;
            }
        }
    }
}
Also used : InsertBatchQuery(org.apache.cayenne.query.InsertBatchQuery) ObjectId(org.apache.cayenne.ObjectId) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) DbAttribute(org.apache.cayenne.map.DbAttribute) InsertBatchQuery(org.apache.cayenne.query.InsertBatchQuery) BatchQuery(org.apache.cayenne.query.BatchQuery) DataRow(org.apache.cayenne.DataRow)

Example 2 with InsertBatchQuery

use of org.apache.cayenne.query.InsertBatchQuery in project cayenne by apache.

the class InsertBatchTranslatorIT method testCreateSqlString.

@Test
public void testCreateSqlString() {
    DbEntity entity = runtime.getDataDomain().getEntityResolver().getObjEntity(SimpleLockingTestEntity.class).getDbEntity();
    DbAdapter adapter = objectFactory.newInstance(DbAdapter.class, JdbcAdapter.class.getName());
    InsertBatchQuery insertQuery = new InsertBatchQuery(entity, 1);
    InsertBatchTranslator builder = new InsertBatchTranslator(insertQuery, adapter);
    String generatedSql = builder.getSql();
    assertNotNull(generatedSql);
    assertEquals("INSERT INTO " + entity.getName() + "( DESCRIPTION, INT_COLUMN_NOTNULL, INT_COLUMN_NULL, LOCKING_TEST_ID, NAME) " + "VALUES( ?, ?, ?, ?, ?)", generatedSql);
}
Also used : JdbcAdapter(org.apache.cayenne.dba.JdbcAdapter) DbEntity(org.apache.cayenne.map.DbEntity) UnitDbAdapter(org.apache.cayenne.unit.UnitDbAdapter) DbAdapter(org.apache.cayenne.dba.DbAdapter) InsertBatchQuery(org.apache.cayenne.query.InsertBatchQuery) SimpleLockingTestEntity(org.apache.cayenne.testdo.locking.SimpleLockingTestEntity) Test(org.junit.Test)

Example 3 with InsertBatchQuery

use of org.apache.cayenne.query.InsertBatchQuery in project cayenne by apache.

the class BatchActionGeneratedIT method testHasGeneratedKeys2.

@Test
public void testHasGeneratedKeys2() throws Exception {
    EntityResolver resolver = runtime.getChannel().getEntityResolver();
    // test with adapter that does not support keys...
    JdbcAdapter adapter = buildAdapter(false);
    InsertBatchQuery batch1 = new InsertBatchQuery(resolver.getObjEntity(GeneratedColumnTestEntity.class).getDbEntity(), 5);
    DataNode node = new DataNode();
    node.setAdapter(adapter);
    node.setEntityResolver(resolver);
    node.setRowReaderFactory(mock(RowReaderFactory.class));
    assertTrue(new BatchAction(batch1, node, false).hasGeneratedKeys());
    assertFalse(new BatchAction(batch1, node, false).supportsGeneratedKeys(true));
}
Also used : JdbcAdapter(org.apache.cayenne.dba.JdbcAdapter) InsertBatchQuery(org.apache.cayenne.query.InsertBatchQuery) DataNode(org.apache.cayenne.access.DataNode) RowReaderFactory(org.apache.cayenne.access.jdbc.reader.RowReaderFactory) EntityResolver(org.apache.cayenne.map.EntityResolver) Test(org.junit.Test)

Example 4 with InsertBatchQuery

use of org.apache.cayenne.query.InsertBatchQuery in project cayenne by apache.

the class DataDomainFlushObserver method nextGeneratedRows.

/**
 * Processes generated keys.
 *
 * @since 1.2
 */
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void nextGeneratedRows(Query query, ResultIterator<?> keysIterator, List<ObjectId> idsToUpdate) {
    // read and close the iterator before doing anything else
    List<DataRow> keys;
    try {
        keys = (List<DataRow>) keysIterator.allRows();
    } finally {
        keysIterator.close();
    }
    if (!(query instanceof InsertBatchQuery)) {
        throw new CayenneRuntimeException("Generated keys only supported for InsertBatchQuery, instead got %s", query);
    }
    if (keys.size() != idsToUpdate.size()) {
        throw new CayenneRuntimeException("Mismatching number of generated PKs: expected %d, instead got %d", idsToUpdate.size(), keys.size());
    }
    for (int i = 0; i < keys.size(); i++) {
        DataRow key = keys.get(i);
        // empty key?
        if (key.size() == 0) {
            throw new CayenneRuntimeException("Empty key generated.");
        }
        ObjectId idToUpdate = idsToUpdate.get(i);
        if (idToUpdate == null || !idToUpdate.isTemporary()) {
            // why would this happen?
            return;
        }
        BatchQuery batch = (BatchQuery) query;
        for (DbAttribute attribute : batch.getDbEntity().getGeneratedAttributes()) {
            // DB DEFAULT values. Ignore those.
            if (attribute.isPrimaryKey()) {
                Object value = key.get(attribute.getName());
                // identity result sets, so a data row may contain garbage labels.
                if (value == null) {
                    value = key.values().iterator().next();
                }
                // Log the generated PK
                logger.logGeneratedKey(attribute, value);
                // I guess we should override any existing value,
                // as generated key is the latest thing that exists in the DB.
                idToUpdate.getReplacementIdMap().put(attribute.getName(), value);
                break;
            }
        }
    }
}
Also used : InsertBatchQuery(org.apache.cayenne.query.InsertBatchQuery) ObjectId(org.apache.cayenne.ObjectId) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) DbAttribute(org.apache.cayenne.map.DbAttribute) InsertBatchQuery(org.apache.cayenne.query.InsertBatchQuery) BatchQuery(org.apache.cayenne.query.BatchQuery) DataRow(org.apache.cayenne.DataRow)

Example 5 with InsertBatchQuery

use of org.apache.cayenne.query.InsertBatchQuery in project cayenne by apache.

the class Oracle8LOBBatchAction method performAction.

@Override
public void performAction(Connection connection, OperationObserver observer) throws SQLException, Exception {
    Oracle8LOBBatchTranslator translator;
    if (query instanceof InsertBatchQuery) {
        translator = new Oracle8LOBInsertBatchTranslator((InsertBatchQuery) query, adapter, OracleAdapter.TRIM_FUNCTION);
    } else if (query instanceof UpdateBatchQuery) {
        translator = new Oracle8LOBUpdateBatchTranslator((UpdateBatchQuery) query, adapter, OracleAdapter.TRIM_FUNCTION);
    } else {
        throw new CayenneRuntimeException("Unsupported batch type for special LOB processing: " + query);
    }
    translator.setNewBlobFunction(OracleAdapter.NEW_BLOB_FUNCTION);
    translator.setNewClobFunction(OracleAdapter.NEW_CLOB_FUNCTION);
    // no batching is done, queries are translated
    // for each batch set, since prepared statements
    // may be different depending on whether LOBs are NULL or not..
    Oracle8LOBBatchQueryWrapper selectQuery = new Oracle8LOBBatchQueryWrapper(query);
    List<DbAttribute> qualifierAttributes = selectQuery.getDbAttributesForLOBSelectQualifier();
    for (BatchQueryRow row : query.getRows()) {
        selectQuery.indexLOBAttributes(row);
        int updated;
        String updateStr = translator.createSql(row);
        // 1. run row update
        logger.log(updateStr);
        try (PreparedStatement statement = connection.prepareStatement(updateStr)) {
            DbAttributeBinding[] bindings = translator.updateBindings(row);
            logger.logQueryParameters("bind", bindings);
            bind(adapter, statement, bindings);
            updated = statement.executeUpdate();
            logger.logUpdateCount(updated);
        }
        // 2. run row LOB update (SELECT...FOR UPDATE and writing out LOBs)
        processLOBRow(connection, translator, selectQuery, qualifierAttributes, row);
        // finally, notify delegate that the row was updated
        observer.nextCount(query, updated);
    }
}
Also used : InsertBatchQuery(org.apache.cayenne.query.InsertBatchQuery) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) DbAttribute(org.apache.cayenne.map.DbAttribute) PreparedStatement(java.sql.PreparedStatement) DbAttributeBinding(org.apache.cayenne.access.translator.DbAttributeBinding) BatchQueryRow(org.apache.cayenne.query.BatchQueryRow) UpdateBatchQuery(org.apache.cayenne.query.UpdateBatchQuery)

Aggregations

InsertBatchQuery (org.apache.cayenne.query.InsertBatchQuery)21 Test (org.junit.Test)11 JdbcAdapter (org.apache.cayenne.dba.JdbcAdapter)9 DbAttribute (org.apache.cayenne.map.DbAttribute)8 DbEntity (org.apache.cayenne.map.DbEntity)7 CayenneRuntimeException (org.apache.cayenne.CayenneRuntimeException)4 ObjectId (org.apache.cayenne.ObjectId)4 DataNode (org.apache.cayenne.access.DataNode)4 RowReaderFactory (org.apache.cayenne.access.jdbc.reader.RowReaderFactory)4 EntityResolver (org.apache.cayenne.map.EntityResolver)4 SimpleLockingTestEntity (org.apache.cayenne.testdo.locking.SimpleLockingTestEntity)4 DataRow (org.apache.cayenne.DataRow)3 DbAdapter (org.apache.cayenne.dba.DbAdapter)3 BatchQuery (org.apache.cayenne.query.BatchQuery)3 UnitDbAdapter (org.apache.cayenne.unit.UnitDbAdapter)3 ArrayList (java.util.ArrayList)2 BatchQueryRow (org.apache.cayenne.query.BatchQueryRow)2 UpdateBatchQuery (org.apache.cayenne.query.UpdateBatchQuery)2 PreparedStatement (java.sql.PreparedStatement)1 HashMap (java.util.HashMap)1