FileDocCategorySizeDatePackage
UpdateStatement.javaAPI DocGlassfish v2 API17666Fri May 04 22:35:16 BST 2007com.sun.jdo.spi.persistence.support.sqlstore.sql.generator

UpdateStatement

public class UpdateStatement extends Statement implements Cloneable
This class is used to generate update/insert/delete statements.

Fields Summary
public int
minAffectedRows
private Map
dbStatementCache
UpdateQueryPlan
plan
The UpdateQueryplan
private List
columnRefsForWhereClause
List of ColumnRef for the where clause used during batch.
private List
versionColumns
List of version columns
private boolean
batch
Flag indicating whether we use batch.
private StringBuffer
values
Insert values for INSERT statements.
private boolean
isConstraintAdded
public static final String
UPDATE_VERSION_COL_PROPERTY
Name of the USE_BATCH property.
private static final boolean
UPDATE_VERSION_COL
Property to swich on/off updating of version col. Note, the default is true, meaning we try to update version col if the property is not specified.
Constructors Summary
public UpdateStatement(com.sun.jdo.spi.persistence.support.sqlstore.database.DBVendorType vendorType, UpdateQueryPlan plan, boolean batch)

 // NOI18N


           
        super(vendorType);
        this.plan = plan;
        columnRefsForWhereClause = new ArrayList();
        this.batch = batch;
        minAffectedRows = 1;
    
Methods Summary
public voidaddColumn(org.netbeans.modules.dbschema.ColumnElement columnElement, java.lang.Object value)

        addColumnRef(new ColumnRef(columnElement, value));
    
protected voidaddConstraint(org.netbeans.modules.dbschema.ColumnElement columnElement, com.sun.jdo.spi.persistence.support.sqlstore.model.LocalFieldDesc lf, java.lang.Object value)
Batch helper method. Adds the columnElement to the list of ColumnRefs for the where clause and then calls addConstraint.

        columnRefsForWhereClause.add(new ColumnRef(columnElement, value));
        addConstraint(lf, value);
    
public voidaddForeignConstraints(int action, com.sun.jdo.spi.persistence.support.sqlstore.model.ForeignFieldDesc f, com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager sm)

        for (int i = 0; i < f.foreignFields.size(); i++) {
            LocalFieldDesc ff = (LocalFieldDesc) f.foreignFields.get(i);

            if (action == QueryPlan.ACT_INSERT) {
                // For inserts into the join table, we get the values we are inserting
                // for the parent object and the added object.
                ColumnElement fc = (ColumnElement) f.assocForeignColumns.get(i);

                addColumn(fc, ff.getValue(sm));
            } else if (action == QueryPlan.ACT_DELETE) {
                LocalFieldDesc aff = (LocalFieldDesc) f.assocForeignFields.get(i);

                // For deletes from the join table, we get the constraint values
                // from the parent object and the remove object.
                addConstraint(aff, ff.getValue(sm));
            }
        }
    
public voidaddLocalConstraints(int action, com.sun.jdo.spi.persistence.support.sqlstore.model.ForeignFieldDesc f, com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager sm)

        for (int i = 0; i < f.localFields.size(); i++) {
            LocalFieldDesc lf = (LocalFieldDesc) f.localFields.get(i);

            if (action == QueryPlan.ACT_INSERT) {
                // For inserts into the join table, we get the values we are inserting
                // for the parent object and the added object.
                ColumnElement lc = (ColumnElement) f.assocLocalColumns.get(i);

                addColumn(lc, lf.getValue(sm));
            } else if (action == QueryPlan.ACT_DELETE) {
                LocalFieldDesc alf = (LocalFieldDesc) f.assocLocalFields.get(i);

                // For deletes from the join table, we get the constraint values
                // from the parent object and the remove object.
                addConstraint(alf, lf.getValue(sm));
            }
        }
    
public voidaddVersionColumn(org.netbeans.modules.dbschema.ColumnElement versionColumn)

        if (versionColumns == null) {
            versionColumns = new ArrayList();
        }
        versionColumns.add(versionColumn);
    
private voidappendVersionColumnUpdateClause(java.lang.StringBuffer setClause)
Appends clause to update version column. The generated clause will be of the following form versionColumnName = versionColumnNane + 1

param
setClause Text for the set clause of update statement

        if(UPDATE_VERSION_COL) {
            if (versionColumns != null)
            {
                for (int i = 0; i < versionColumns.size(); i++) {
                    ColumnElement columnElement = (ColumnElement) versionColumns.get(i);
                    String columnName = columnElement.getName().getName();
                    setClause.append(", ");
                    appendQuotedText(setClause, columnName);
                    setClause.append(" = ");
                    appendQuotedText(setClause, columnName);
                    setClause.append(" + ");
                    setClause.append("1");
                }
            }
        }
    
private voidbindInputColumn(DBStatement stmt, ColumnRef columnRef, com.sun.jdo.spi.persistence.support.sqlstore.sql.UpdateObjectDescImpl updateDesc, boolean getBeforeValue)
Binds the value in the specified update descriptor corresponding with the specified column reference to the specified statement.

param
stmt the statement
param
columnRef the column reference
param
updateDesc the update descriptor
throws
SQLException thrown by setter methods on java.sql.PreparedStatement


        Object inputValue = getInputValue(updateDesc, columnRef, getBeforeValue);
        stmt.bindInputColumn(columnRef.getIndex(), inputValue,
                columnRef.getColumnElement(), vendorType);
    
public voidbindInputColumns(DBStatement s, com.sun.jdo.spi.persistence.support.sqlstore.sql.UpdateObjectDescImpl updateDesc)


        // bind set clause (if necessary)
        for (Iterator i = getColumnRefs().iterator(); i.hasNext(); ) {
            bindInputColumn(s, (ColumnRef)i.next(), updateDesc, false );
        }
        // bind where clause (if necessary)
        for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) {
            bindInputColumn(s, (ColumnRef) i.next(), updateDesc,
                    updateDesc.isBeforeImageRequired());
        }

    
private voidcalculateWhereClauseColumnRefIndexes()
Calculates the index of the where clause ColumnRefs

        // calculate where clause column ref indexes
        // NOTE, the sqlstore processes the constraints in reverse order,
        // so start with the last index and decrement
        int nextIndex = columns.size() + columnRefsForWhereClause.size();
        for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) {
            ColumnRef columnRef = (ColumnRef)i.next();
            columnRef.setIndex(nextIndex--);
        }
    
public booleanexceedsBatchThreshold(com.sun.jdo.spi.persistence.support.sqlstore.Transaction tran)

        synchronized (dbStatementCache)
        {
            DBStatement dbStatement = (DBStatement)dbStatementCache.get(tran);
            return (dbStatement != null) && dbStatement.exceedsBatchThreshold();
        }
    
private java.lang.StringBuffergenerateColumnText()

        StringBuffer columnList = new StringBuffer();
        int numValues = -1;

        for (int i = 0; i < columns.size(); i++) {
            ColumnRef c = (ColumnRef) columns.get(i);

            if (columnList.length() > 0) {
                columnList.append(", "); // NOI18N
            }
            switch (action) {
                case QueryPlan.ACT_UPDATE:
                    appendQuotedText(columnList, c.getName());
                    columnList.append("= ?"); // NOI18N
                    break;

                case QueryPlan.ACT_INSERT:
                    appendQuotedText(columnList, c.getName());
                    if (i == 0) {
                        values = new StringBuffer().append(" ?"); // NOI18N
                    } else {
                        values.append(", ?"); // NOI18N
                    }
                    break;
            }

            // Do not create an InputValue in the case of batch update.
            // Method bindInputValues will get the value using the ColumnRef.
            if (!batch &&
                ((action == QueryPlan.ACT_UPDATE) ||
                    (action == QueryPlan.ACT_INSERT))) {
                numValues = numValues + 1;
                InputValue val = new InputValue(c.getValue(), c.getColumnElement());
                inputDesc.values.add(numValues, val);
            }
        }

        appendVersionColumnUpdateClause(columnList);

        return columnList;
    
protected voidgenerateStatementText()

inheritDoc


        statementText = new StringBuffer();

        StringBuffer columnList = generateColumnText();
        StringBuffer constraint = processConstraints();
        String tableName = ((QueryTable) tableList.get(0)).getTableDesc().getName();

        // Create the query filling in the column list, table name, etc.
        switch (action) {
            case QueryPlan.ACT_UPDATE:
                statementText.append("update ");// NOI18N
                appendQuotedText(statementText, tableName);
                statementText.append(" set ").append(columnList).append(" where ").append(constraint); // NOI18N
                break;

            case QueryPlan.ACT_DELETE:
                statementText.append("delete from ");// NOI18N
                appendQuotedText(statementText, tableName);
                statementText.append(" where ").append(constraint); // NOI18N
                break;

            case QueryPlan.ACT_INSERT:
                statementText.append("insert into ");// NOI18N
                appendQuotedText(statementText, tableName);
                statementText.append("(").append(columnList).// NOI18N
                        append(") values ").append("(").append(values).append(")"); // NOI18N
                break;
        }

        calculateWhereClauseColumnRefIndexes();
    
public DBStatementgetDBStatement(com.sun.jdo.spi.persistence.support.sqlstore.Transaction tran, java.sql.Connection conn)
Returns the cached db statement for the specified connection. If there is not any statement for this connection in the cache, then a new statement is created.

param
tran the transaction
param
conn the connection
return
the statement

        DBStatement dbStatement = null;

        synchronized (dbStatementCache)
        {
            // dbStatement cachelookup
            dbStatement = (DBStatement)dbStatementCache.get(tran);

            if (dbStatement == null) {
                dbStatement = new DBStatement(conn, getText(),
                                              tran.getUpdateTimeout());
                // put dbStatement in cache
                dbStatementCache.put(tran, dbStatement);
            }
        }

        return dbStatement;
    
public java.lang.StringgetFormattedSQLText(com.sun.jdo.spi.persistence.support.sqlstore.sql.UpdateObjectDescImpl updateDesc)
Gets formatted sql text corrsponding to this statement object. The text also contains values for input to the statement.

param
updateDesc the updateDesc.
return
formatted sql text corrsponding to this statement object.

        return formatSqlText(getText(), getInputValues(updateDesc));
    
private static java.lang.ObjectgetInputValue(com.sun.jdo.spi.persistence.support.sqlstore.sql.UpdateObjectDescImpl updateDesc, ColumnRef columnRef, boolean getBeforeValue)
Gets input value corrsponding to given columnRef from given updateDesc

param
updateDesc updateDesc pointing to the input values
param
columnRef The columnRef. It always contains the LocalFieldDesc for the field.
param
getBeforeValue If true, value returned is fetched from beforeImage if false, the value returned is fetched from afterImage.
return
input value corrsponding to given columnRef from given updateDesc.

        Object value;
        LocalFieldDesc field = (LocalFieldDesc) columnRef.getValue();

        if (field.isVersion()) {
            // Bind the value from the after image for version fields,
            // as they're incremented internally after each flush.
            // Version fields must not be modified from "outside".
            value = updateDesc.getAfterValue(field);
        }  else {
            value = getBeforeValue ? updateDesc.getBeforeValue(field) :
                    updateDesc.getAfterValue(field);
        }

        return value;
    
private java.lang.Object[]getInputValues(com.sun.jdo.spi.persistence.support.sqlstore.sql.UpdateObjectDescImpl updateDesc)
Get Input values to be bound to this statement.

param
updateDesc The update descriptor.
return
An Object array containing input values to be bound to this statement.

        Object[] inputValues =
                new Object[getColumnRefs().size() + columnRefsForWhereClause.size()];
        for (Iterator i = getColumnRefs().iterator(); i.hasNext(); ) {
            ColumnRef columnRef = (ColumnRef)i.next();
            // columnRef's index are 1 based.
            inputValues[columnRef.getIndex() - 1] = getInputValue(updateDesc, columnRef, false);
        }
        final boolean getBeforeValue = updateDesc.isBeforeImageRequired();
        for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) {
            ColumnRef columnRef = (ColumnRef)i.next();
            inputValues[columnRef.getIndex() - 1] = getInputValue(updateDesc, columnRef, getBeforeValue);
        }
        return inputValues;
    
public QueryPlangetQueryPlan()

inheritDoc

         return plan;
    
public booleanisConstraintAdded()

        return isConstraintAdded;
    
public voidmarkConstraintAdded()

        isConstraintAdded = true;
    
protected voidprocessConstraintValue(com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint.ConstraintValue node, java.lang.StringBuffer result)
Redefines processConstraintValue in order to skip the creation of an InputValue in the case of batch.

        result.append("?"); // NOI18N
        if (!batch)
            generateInputValueForConstraintValueNode(node);
    
public DBStatementremoveDBStatement(com.sun.jdo.spi.persistence.support.sqlstore.Transaction tran)
Removes the db statement for the specified connection from the cache and closes this statement.

param
tran the transaction

        synchronized (dbStatementCache)
        {
            DBStatement s = (DBStatement)dbStatementCache.remove(tran);
            return s;
        }