Search in sources :

Example 66 with CayenneRuntimeException

use of org.apache.cayenne.CayenneRuntimeException in project cayenne by apache.

the class FrontBasePkGenerator method longPkFromDatabase.

/**
 * @since 3.0
 */
@Override
protected long longPkFromDatabase(DataNode node, DbEntity entity) throws Exception {
    String template = "SELECT #result('UNIQUE' 'long') FROM " + entity.getName();
    final long[] pkHolder = new long[1];
    SQLTemplate query = new SQLTemplate(entity, template);
    OperationObserver observer = new DoNothingOperationObserver() {

        @Override
        public void nextRows(Query query, List<?> dataRows) {
            if (dataRows.size() != 1) {
                throw new CayenneRuntimeException("Error fetching PK. Expected one row, got %d", dataRows.size());
            }
            DataRow row = (DataRow) dataRows.get(0);
            Number pk = (Number) row.get("UNIQUE");
            pkHolder[0] = pk.longValue();
        }
    };
    node.performQueries(Collections.singleton((Query) query), observer);
    return pkHolder[0];
}
Also used : SQLTemplate(org.apache.cayenne.query.SQLTemplate) Query(org.apache.cayenne.query.Query) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) OperationObserver(org.apache.cayenne.access.OperationObserver) DoNothingOperationObserver(org.apache.cayenne.access.util.DoNothingOperationObserver) ArrayList(java.util.ArrayList) List(java.util.List) DoNothingOperationObserver(org.apache.cayenne.access.util.DoNothingOperationObserver) DataRow(org.apache.cayenne.DataRow)

Example 67 with CayenneRuntimeException

use of org.apache.cayenne.CayenneRuntimeException in project cayenne by apache.

the class HSQLDBAdapter method createUniqueConstraint.

/**
 * Returns a DDL string to create a unique constraint over a set of columns.
 *
 * @since 1.1
 */
@Override
public String createUniqueConstraint(DbEntity source, Collection<DbAttribute> columns) {
    if (columns == null || columns.isEmpty()) {
        throw new CayenneRuntimeException("Can't create UNIQUE constraint - no columns specified.");
    }
    String srcName = getTableName(source);
    StringBuilder buf = new StringBuilder();
    buf.append("ALTER TABLE ").append(srcName);
    buf.append(" ADD CONSTRAINT ");
    String name = "U_" + source.getName() + "_" + (long) (System.currentTimeMillis() / (Math.random() * 100000));
    buf.append(quotingStrategy.quotedIdentifier(source, source.getSchema(), name));
    buf.append(" UNIQUE (");
    Iterator<DbAttribute> it = columns.iterator();
    DbAttribute first = it.next();
    buf.append(quotingStrategy.quotedName(first));
    while (it.hasNext()) {
        DbAttribute next = it.next();
        buf.append(", ");
        buf.append(quotingStrategy.quotedName(next));
    }
    buf.append(")");
    return buf.toString();
}
Also used : CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) DbAttribute(org.apache.cayenne.map.DbAttribute)

Example 68 with CayenneRuntimeException

use of org.apache.cayenne.CayenneRuntimeException in project cayenne by apache.

the class SybasePkGenerator method longPkFromDatabase.

/**
 * @since 3.0
 */
@Override
protected long longPkFromDatabase(DataNode node, DbEntity entity) throws Exception {
    // handle CAY-588 - get connection that is separate from the connection
    // in the current transaction.
    // TODO (andrus, 7/6/2006) Note that this will still work in a pool with
    // a single connection, as PK generator is invoked early in the transaction,
    // before the connection is grabbed for commit...
    // So maybe promote this to other adapters in 3.0?
    Transaction transaction = BaseTransaction.getThreadTransaction();
    BaseTransaction.bindThreadTransaction(null);
    try (Connection connection = node.getDataSource().getConnection()) {
        try (CallableStatement statement = connection.prepareCall("{call auto_pk_for_table(?, ?)}")) {
            statement.setString(1, entity.getName());
            statement.setInt(2, super.getPkCacheSize());
            // can't use "executeQuery" per http://jtds.sourceforge.net/faq.html#expectingResultSet
            statement.execute();
            if (statement.getMoreResults()) {
                try (ResultSet rs = statement.getResultSet()) {
                    if (rs.next()) {
                        return rs.getLong(1);
                    } else {
                        throw new CayenneRuntimeException("Error generating pk for DbEntity %s", entity.getName());
                    }
                }
            } else {
                throw new CayenneRuntimeException("Error generating pk for DbEntity %s" + ", no result set from stored procedure.", entity.getName());
            }
        }
    } finally {
        BaseTransaction.bindThreadTransaction(transaction);
    }
}
Also used : BaseTransaction(org.apache.cayenne.tx.BaseTransaction) Transaction(org.apache.cayenne.tx.Transaction) CallableStatement(java.sql.CallableStatement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException)

Example 69 with CayenneRuntimeException

use of org.apache.cayenne.CayenneRuntimeException in project cayenne by apache.

the class ObjRelationship method getReverseDbRelationshipPath.

/**
 * Returns a reversed dbRelationship path.
 *
 * @since 1.2
 */
public String getReverseDbRelationshipPath() throws ExpressionException {
    List<DbRelationship> relationships = getDbRelationships();
    if (relationships == null || relationships.isEmpty()) {
        return null;
    }
    StringBuilder buffer = new StringBuilder();
    // iterate in reverse order
    ListIterator<DbRelationship> it = relationships.listIterator(relationships.size());
    while (it.hasPrevious()) {
        DbRelationship relationship = it.previous();
        DbRelationship reverse = relationship.getReverseRelationship();
        // another sanity check
        if (reverse == null) {
            throw new CayenneRuntimeException("No reverse relationship exist for %s", relationship);
        }
        if (buffer.length() > 0) {
            buffer.append(Entity.PATH_SEPARATOR);
        }
        buffer.append(reverse.getName());
    }
    return buffer.toString();
}
Also used : ToStringBuilder(org.apache.cayenne.util.ToStringBuilder) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException)

Example 70 with CayenneRuntimeException

use of org.apache.cayenne.CayenneRuntimeException in project cayenne by apache.

the class MappedSelect method createReplacementQuery.

@Override
protected Query createReplacementQuery(EntityResolver resolver) {
    QueryDescriptor descriptor = resolver.getQueryDescriptor(queryName);
    Query query = super.createReplacementQuery(resolver);
    QueryCacheStrategy cacheStrategyOverride = null;
    if (forceNoCache) {
        QueryCacheStrategy cacheStrategy = query.getMetaData(resolver).getCacheStrategy();
        if (QueryCacheStrategy.LOCAL_CACHE == cacheStrategy) {
            cacheStrategyOverride = QueryCacheStrategy.LOCAL_CACHE_REFRESH;
        } else if (QueryCacheStrategy.SHARED_CACHE == cacheStrategy) {
            cacheStrategyOverride = QueryCacheStrategy.SHARED_CACHE_REFRESH;
        }
    }
    switch(descriptor.getType()) {
        case QueryDescriptor.SELECT_QUERY:
            SelectQuery selectQuery = (SelectQuery) query;
            if (fetchLimit != null) {
                selectQuery.setFetchLimit(fetchLimit);
            }
            if (fetchOffset != null) {
                selectQuery.setFetchOffset(fetchOffset);
            }
            if (statementFetchSize != null) {
                selectQuery.setStatementFetchSize(statementFetchSize);
            }
            if (pageSize != null) {
                selectQuery.setPageSize(pageSize);
            }
            if (cacheStrategyOverride != null) {
                selectQuery.setCacheStrategy(cacheStrategyOverride);
            }
            break;
        case QueryDescriptor.SQL_TEMPLATE:
            SQLTemplate sqlTemplate = (SQLTemplate) query;
            if (fetchLimit != null) {
                sqlTemplate.setFetchLimit(fetchLimit);
            }
            if (fetchOffset != null) {
                sqlTemplate.setFetchOffset(fetchOffset);
            }
            if (statementFetchSize != null) {
                sqlTemplate.setStatementFetchSize(statementFetchSize);
            }
            if (pageSize != null) {
                sqlTemplate.setPageSize(pageSize);
            }
            if (cacheStrategyOverride != null) {
                sqlTemplate.setCacheStrategy(cacheStrategyOverride);
            }
            break;
        case QueryDescriptor.EJBQL_QUERY:
            EJBQLQuery ejbqlQuery = (EJBQLQuery) query;
            if (fetchLimit != null) {
                ejbqlQuery.setFetchLimit(fetchLimit);
            }
            if (fetchOffset != null) {
                ejbqlQuery.setFetchOffset(fetchOffset);
            }
            if (statementFetchSize != null) {
                ejbqlQuery.setStatementFetchSize(statementFetchSize);
            }
            if (pageSize != null) {
                ejbqlQuery.setPageSize(pageSize);
            }
            if (cacheStrategyOverride != null) {
                ejbqlQuery.setCacheStrategy(cacheStrategyOverride);
            }
            break;
        case QueryDescriptor.PROCEDURE_QUERY:
            ProcedureQuery procedureQuery = (ProcedureQuery) query;
            if (fetchLimit != null) {
                procedureQuery.setFetchLimit(fetchLimit);
            }
            if (fetchOffset != null) {
                procedureQuery.setFetchOffset(fetchOffset);
            }
            if (statementFetchSize != null) {
                procedureQuery.setStatementFetchSize(statementFetchSize);
            }
            if (pageSize != null) {
                procedureQuery.setPageSize(pageSize);
            }
            if (cacheStrategyOverride != null) {
                procedureQuery.setCacheStrategy(cacheStrategyOverride);
            }
            break;
        default:
            throw new CayenneRuntimeException("Unknown query type: %s", descriptor.getType());
    }
    return query;
}
Also used : QueryDescriptor(org.apache.cayenne.map.QueryDescriptor) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException)

Aggregations

CayenneRuntimeException (org.apache.cayenne.CayenneRuntimeException)168 Test (org.junit.Test)25 DbAttribute (org.apache.cayenne.map.DbAttribute)21 DataMap (org.apache.cayenne.map.DataMap)19 ObjectId (org.apache.cayenne.ObjectId)18 ObjEntity (org.apache.cayenne.map.ObjEntity)18 Persistent (org.apache.cayenne.Persistent)17 Expression (org.apache.cayenne.exp.Expression)17 ClassDescriptor (org.apache.cayenne.reflect.ClassDescriptor)17 ArrayList (java.util.ArrayList)14 HashMap (java.util.HashMap)14 DbEntity (org.apache.cayenne.map.DbEntity)14 IOException (java.io.IOException)13 List (java.util.List)12 ObjRelationship (org.apache.cayenne.map.ObjRelationship)12 DbRelationship (org.apache.cayenne.map.DbRelationship)10 DateTestEntity (org.apache.cayenne.testdo.date_time.DateTestEntity)10 File (java.io.File)9 Connection (java.sql.Connection)9 SQLException (java.sql.SQLException)9