db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From d..@apache.org
Subject svn commit: r1517823 [2/2] - in /db/derby/code/trunk: java/engine/org/apache/derby/iapi/sql/dictionary/ java/engine/org/apache/derby/impl/sql/catalog/ java/engine/org/apache/derby/impl/sql/compile/ java/engine/org/apache/derby/impl/sql/execute/ java/en...
Date Tue, 27 Aug 2013 14:05:04 GMT
Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/SetConstraintsConstantAction.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/SetConstraintsConstantAction.java?rev=1517823&r1=1517822&r2=1517823&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/SetConstraintsConstantAction.java
(original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/SetConstraintsConstantAction.java
Tue Aug 27 14:05:03 2013
@@ -23,9 +23,11 @@ package org.apache.derby.impl.sql.execut
 
 import java.util.Enumeration;
 import java.util.Hashtable;
+import java.util.List;
 
 import org.apache.derby.catalog.UUID;
 import org.apache.derby.iapi.error.StandardException;
+import org.apache.derby.iapi.reference.SQLState;
 import org.apache.derby.iapi.services.context.ContextManager;
 import org.apache.derby.iapi.services.io.FormatableBitSet;
 import org.apache.derby.shared.common.sanity.SanityManager;
@@ -39,6 +41,7 @@ import org.apache.derby.iapi.sql.diction
 import org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor;
 import org.apache.derby.iapi.sql.dictionary.IndexRowGenerator;
 import org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor;
+import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
 import org.apache.derby.iapi.sql.dictionary.TableDescriptor;
 import org.apache.derby.iapi.sql.execute.ConstantAction;
 import org.apache.derby.iapi.sql.execute.ExecIndexRow;
@@ -46,6 +49,7 @@ import org.apache.derby.iapi.sql.execute
 import org.apache.derby.iapi.store.access.ConglomerateController;
 import org.apache.derby.iapi.store.access.TransactionController;
 import org.apache.derby.iapi.types.RowLocation;
+import org.apache.derby.impl.sql.compile.TableName;
 
 /**
  * This class describes actions that are performed for a
@@ -60,47 +64,23 @@ import org.apache.derby.iapi.types.RowLo
 class SetConstraintsConstantAction extends DDLConstantAction
 {
 
-	private boolean 					enable;
-	private	boolean						unconditionallyEnforce;
+    final private boolean   initiallyDeferred;
+    private List<TableName> constraints;
 
-	/*
-	** For the following fields, never access directly, always
-	** get the constraint descript list via the private
-	** method getConstraintDescriptorList() defined herein.
-	*/
-	private ConstraintDescriptorList	cdl;
-	private UUID[]						cuuids;
-	private UUID[]						tuuids;
 
 	// CONSTRUCTORS
-	/**
-	 *Boilerplate
-	 *
-	 * @param cdl						ConstraintDescriptorList
-	 * @param enable					true == turn them on, false == turn them off
-	 * @param unconditionallyEnforce	Replication sets this to true at
-	 *									the end of REFRESH. This forces us
-	 *									to run the included foreign key constraints even
-	 *									if they're already marked ENABLED.
-	 */
-	SetConstraintsConstantAction
-	(
-		ConstraintDescriptorList	cdl,
-		boolean						enable,
-		boolean						unconditionallyEnforce
-	)
-	{
-		this.cdl = cdl;
-		this.enable = enable;
-		this.unconditionallyEnforce = unconditionallyEnforce;
+    /**
+     * @param constraints               List of constraints to set; null if all.
+     * @param initiallyDeferred         Encodes IMMEDIATE (false), DEFERRED (true)
+     */
+    SetConstraintsConstantAction(
+            List<TableName>             constraints,
+            boolean                     initiallyDeferred) {
+        this.constraints = constraints;
+        this.initiallyDeferred = initiallyDeferred;
 	}
 
-	//////////////////////////////////////////////////////////////
-	//
-	// OBJECT SHADOWS
-	//
-	//////////////////////////////////////////////////////////////
-
+    @Override
 	public	String	toString()
 	{
 		// Do not put this under SanityManager.DEBUG - it is needed for
@@ -108,9 +88,6 @@ class SetConstraintsConstantAction exten
 		return "SET CONSTRAINTS";
 	}
 
-	// INTERFACE METHODS
-
-
 	/**
 	 *	This is the guts of the Execution-time logic for DROP CONSTRAINT.
 	 *
@@ -118,367 +95,39 @@ class SetConstraintsConstantAction exten
 	 *
 	 * @exception StandardException		Thrown on failure
 	 */
-	public void	executeConstantAction( Activation activation )
-						throws StandardException
-	{
-		ConstraintDescriptor		cd;
-		TableDescriptor				td;
-		ConstraintDescriptorList	tmpCdl;
-		boolean						enforceThisConstraint;
-
-		LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
-		DataDictionary dd = lcc.getDataDictionary();
-		DependencyManager dm = dd.getDependencyManager();
-		TransactionController tc = lcc.getTransactionExecute();
-
-		tmpCdl = getConstraintDescriptorList(dd);
-
-		int[] enabledCol = new int[1];
-		enabledCol[0] = ConstraintDescriptor.SYSCONSTRAINTS_STATE_FIELD;
-		/*
-		** Inform the data dictionary that we are about to write to it.
-		** There are several calls to data dictionary "get" methods here
-		** that might be done in "read" mode in the data dictionary, but
-		** it seemed safer to do this whole operation in "write" mode.
-		**
-		** We tell the data dictionary we're done writing at the end of
-		** the transaction.
-		*/
-		dd.startWriting(lcc);
-
-		/*
-		** Callback to rep subclass
-		*/
-		publishToTargets(activation);
-
-		boolean skipFKs = false;
-
-		/*
-		** If the constraint list is empty, then we are getting
-		** all constraints.  In this case, don't bother going
-		** after referencing keys (foreign keys) when we are 
-		** disabling a referenced key (pk or unique key) since
-		** we know we'll hit it eventually.	
-		*/
-		if (tmpCdl == null)
-		{
-			skipFKs = true;
-			tmpCdl = dd.getConstraintDescriptors((TableDescriptor)null);
-		}
-	
-		Hashtable<UUID,ConstraintDescriptorList> checkConstraintTables = null;
-		int cdlSize = tmpCdl.size();
-		for (int index = 0; index < cdlSize; index++)
-		{
-			cd = tmpCdl.elementAt(index);
-
-			/*	
-			** We are careful to enable this constraint before trying
-			** to enable constraints that reference it.  Similarly,
-			** we disabled constraints that reference us before we
-			** disable ourselves, to make sure everything works ok.
-			*/
-			if (unconditionallyEnforce) 
-			{ 
-				enforceThisConstraint = true; 
-			}
-			else 
-			{ 
-				enforceThisConstraint = (enable && !cd.isEnabled()); 
-			}
-
-			if (enforceThisConstraint)
-			{
-				if (cd instanceof ForeignKeyConstraintDescriptor)
-				{
-					validateFKConstraint((ForeignKeyConstraintDescriptor)cd, dd, tc, lcc.getContextManager());
-				}
-				/*
-				** For check constraints, we build up a list of check constriants
-				** by table descriptor.  Once we have collected them all, we
-				** execute them in a single query per table descriptor.
-				*/
-				else if (cd instanceof CheckConstraintDescriptor)
-				{
-					td = cd.getTableDescriptor();
-
-					if (checkConstraintTables == null)
-					{
-						checkConstraintTables = new Hashtable<UUID,ConstraintDescriptorList>(10);
-					}
-
-					ConstraintDescriptorList tabCdl =
-												checkConstraintTables.get(td.getUUID());
-					if (tabCdl == null)
-					{
-						tabCdl = new ConstraintDescriptorList();
-						checkConstraintTables.put(td.getUUID(), tabCdl);
-					}
-					tabCdl.add(cd);
-				}
-				/*
-				** If we are enabling a constraint, we need to issue
-				** the invalidation on the underlying table rather than
-				** the constraint we are enabling.  This is because
-				** stmts that were compiled against a disabled constraint
-				** have no depedency on that disabled constriant.
-				*/
-				dm.invalidateFor(cd.getTableDescriptor(), 
-									DependencyManager.SET_CONSTRAINTS_ENABLE, lcc);
-				cd.setEnabled();
-				dd.updateConstraintDescriptor(cd, 
-											cd.getUUID(), 
-											enabledCol, 
-											tc);
-			}
-	
-			/*
-			** If we are dealing with a referenced constraint, then
-			** we find all of the constraints that reference this constraint.
-			** Turn them on/off based on what we are doing to this
-			** constraint.
-			*/
-			if (!skipFKs &&
-				(cd instanceof ReferencedKeyConstraintDescriptor))
-			{
-				ForeignKeyConstraintDescriptor fkcd;
-				ReferencedKeyConstraintDescriptor refcd;
-				ConstraintDescriptorList fkcdl;
-	
-				refcd = (ReferencedKeyConstraintDescriptor)cd;
-				fkcdl = refcd.getForeignKeyConstraints(ReferencedKeyConstraintDescriptor.ALL);
-
-				int fkcdlSize = fkcdl.size();
-				for (int inner = 0; inner < fkcdlSize; inner++)
-				{
-					fkcd = (ForeignKeyConstraintDescriptor) fkcdl.elementAt(inner);	
-					if (enable && !fkcd.isEnabled())
-					{
-						dm.invalidateFor(fkcd.getTableDescriptor(), 
-									DependencyManager.SET_CONSTRAINTS_ENABLE, lcc);
-						validateFKConstraint(fkcd, dd, tc, lcc.getContextManager());
-						fkcd.setEnabled();
-						dd.updateConstraintDescriptor(fkcd, 
-								fkcd.getUUID(), 
-								enabledCol, 
-								tc);
-					}
-					else if (!enable && fkcd.isEnabled())
-					{
-						dm.invalidateFor(fkcd, DependencyManager.SET_CONSTRAINTS_DISABLE,
-										 lcc);
-						fkcd.setDisabled();
-						dd.updateConstraintDescriptor(fkcd, 
-								fkcd.getUUID(), 
-								enabledCol, 
-								tc);
-					}
-				}
-			}
-	
-			if (!enable && cd.isEnabled())
-			{
-				dm.invalidateFor(cd, DependencyManager.SET_CONSTRAINTS_DISABLE,
-								 lcc);
-				cd.setDisabled();
-				dd.updateConstraintDescriptor(cd, 
-												cd.getUUID(), 
-												enabledCol, 
-												tc);
-			}
-		}
-
-		validateAllCheckConstraints(lcc, checkConstraintTables);
-	}
-
-	private void validateAllCheckConstraints(LanguageConnectionContext lcc, Hashtable<UUID,ConstraintDescriptorList>
ht)
-		throws StandardException
-	{
-		ConstraintDescriptorList	cdl;
-		ConstraintDescriptor		cd = null;
-		TableDescriptor				td;
-		StringBuffer				text;
-		StringBuffer				constraintNames;
-
-		if (ht == null)
-		{
-			return;
-		}
-
-		for (Enumeration<ConstraintDescriptorList> e = ht.elements(); e.hasMoreElements();
)
-		{
-		
-			cdl = e.nextElement();
-			text = null;
-			constraintNames = null;
-
-			/*
-			** Build up the text of all the constraints into one big
-			** predicate.  Also, we unfortunately have to build up a big
-			** comma separated list of constraint names in case
-			** there is an error (we are favoring speed over a very
-			** explicit check constraint xxxx failed error message).
-			*/
-			int cdlSize = cdl.size();
-			for (int index = 0; index < cdlSize; index++)
-			{
-				cd = (ConstraintDescriptor) cdl.elementAt(index);
-				if (text == null)
-				{
-					text = new StringBuffer("(").append(cd.getConstraintText()).append(") ");
-					constraintNames = new StringBuffer(cd.getConstraintName());
-				}
-				else
-				{
-					text.append(" AND (").append(cd.getConstraintText()).append(") ");
-					constraintNames.append(", ").append(cd.getConstraintName());
-				}
-			}
-
-			if (SanityManager.DEBUG)
-			{
-				SanityManager.ASSERT(text != null, "internal error, badly built hastable");
-			}
-
-			ConstraintConstantAction.validateConstraint(
-												constraintNames.toString(),
-												text.toString(),
-												cd.getTableDescriptor(),
-												lcc, true);
-		}
-	}
+    public void executeConstantAction(
+            Activation activation) throws StandardException {
 
-	/*
-	**
-	*/
-	private void validateFKConstraint
-	(
-		ForeignKeyConstraintDescriptor	fk,
-		DataDictionary					dd,
-		TransactionController			tc,
-		ContextManager					cm
-	)
-		throws StandardException
-	{
-		/*
-		** Construct a template row 
-		*/
-		IndexRowGenerator irg = fk.getIndexConglomerateDescriptor(dd).getIndexDescriptor();	
-		ExecIndexRow indexTemplateRow = irg.getIndexRowTemplate();
-		TableDescriptor td = fk.getTableDescriptor();
-		ExecRow baseRow = td.getEmptyExecRow();
-		irg.getIndexRow(baseRow, getRowLocation(dd, td, tc), 
-								indexTemplateRow, (FormatableBitSet)null);
-
-		/*
-		** The moment of truth
-		*/
-		ConstraintConstantAction.validateFKConstraint(tc, dd, fk, 
-							fk.getReferencedConstraint(), indexTemplateRow);
-	}
-			
-	/*
-	** Get a row location template.  Note that we are assuming that
-	** the same row location can be used for all tables participating
-	** in the fk.  For example, if there are multiple foreign keys,
-	** we are using the row location of one of the tables and assuming
-	** that it is the right shape for all tables.  Currently, this
-	** is a legitimate assumption.
-	*/
-	private RowLocation getRowLocation
-	(
-		DataDictionary			dd, 
-		TableDescriptor			td,
-		TransactionController	tc
-	) 
-		throws StandardException
-	{
-		RowLocation 			rl; 
-		ConglomerateController 	heapCC = null;
-
-		long tableId = td.getHeapConglomerateId();
-		heapCC = 
-            tc.openConglomerate(
-                tableId, false, 0, tc.MODE_RECORD, tc.ISOLATION_READ_COMMITTED);
-		try
-		{
-			rl = heapCC.newRowLocationTemplate();
-		}
-		finally
-		{
-			heapCC.close();
-		}
+        final LanguageConnectionContext lcc =
+                activation.getLanguageConnectionContext();
 
-		return rl;
-	}
-		
-	/*
-	** Wrapper for constraint descriptor list -- always use
-	** this to get the constriant descriptor list.  It is
-	** used to hide serialization.
-	*/
-	private ConstraintDescriptorList getConstraintDescriptorList(DataDictionary dd)
-		throws StandardException
-	{
-		if (cdl != null)
-		{
-			return cdl;
-		}
-		if (tuuids == null)
-		{
-			return null;
-		}
-
-		/*
-		** Reconstitute the cdl from the uuids
-		*/
-		cdl = new ConstraintDescriptorList();
-
-		for (int i = 0; i < tuuids.length; i++)
-		{
-			TableDescriptor td = dd.getTableDescriptor(tuuids[i]);
-			if (SanityManager.DEBUG)
-			{
-				if (td == null)
-				{
-					SanityManager.THROWASSERT("couldn't locate table descriptor "+
-						"in SET CONSTRAINTS for uuid "+tuuids[i]);
-				}
-			}
-
-			ConstraintDescriptor cd = dd.getConstraintDescriptorById(td, cuuids[i]);
-
-			if (SanityManager.DEBUG)
-			{
-				if (cd == null)
-				{
-					SanityManager.THROWASSERT("couldn't locate constraint descriptor "+
-						" in SET CONSTRAINTS for uuid "+cuuids[i]);
-				}
-			}
-
-			cdl.add(cd);
-		}
-		return cdl;
-	}
-		
-	///////////////////////////////////////////////
-	//
-	// MISC
-	//
-	///////////////////////////////////////////////
+        final DataDictionary dd = lcc.getDataDictionary();
+        ConstraintDescriptorList cl = new ConstraintDescriptorList();
 
-	/**
-	 * Do the work of publishing any this action to any
-	 * replication targets.  On a non-replicated source,
-	 * this is a no-op.
-	 *
-	 * @param activation the activation
-	 *
-	 * @exception StandardException on error
-	 */
-	protected void publishToTargets(Activation activation)
-		throws StandardException
-	{
-	}
+        if (constraints != null) {
+            for (TableName c : constraints) {
+                SchemaDescriptor sd = dd.getSchemaDescriptor(
+                    c.getSchemaName(),
+                    lcc.getTransactionExecute(),
+                    true);
+
+                ConstraintDescriptor cd =
+                    dd.getConstraintDescriptor(c.getTableName(), sd.getUUID());
+
+                if (cd == null) {
+                    throw StandardException.newException(
+                            SQLState.LANG_OBJECT_NOT_FOUND,
+                            "CONSTRAINT",
+                            c.getFullSQLName());
+                }
+
+                cl.add(cd);
+            }
+        } else {
+            cl = dd.getConstraintDescriptors(null); // all
+        }
+
+        throw StandardException.newException(SQLState.NOT_IMPLEMENTED,
+                       "SET CONSTRAINT");
+    }
 }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/UpdatableVTIConstantAction.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/UpdatableVTIConstantAction.java?rev=1517823&r1=1517822&r2=1517823&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/UpdatableVTIConstantAction.java
(original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/UpdatableVTIConstantAction.java
Tue Aug 27 14:05:03 2013
@@ -57,13 +57,15 @@ public class UpdatableVTIConstantAction 
 	/**
 	 *	Make the ConstantAction for an updatable VTI statement.
 	 *
+     * @param statementType             Statement type, cf.
+     * {@link org.apache.derby.vti.DeferModification#INSERT_STATEMENT} etc.
 	 * @param deferred					Whether or not to do operation in deferred mode
      * @param changedColumnIds Array of ids of changed columns
 	 *
 	 */
     UpdatableVTIConstantAction(int statementType,
-                                        boolean deferred,
-                                        int[] changedColumnIds)
+                               boolean deferred,
+                               int[] changedColumnIds)
 	{
 		super(0, 
 			  null,

Modified: db/derby/code/trunk/java/engine/org/apache/derby/loc/messages.xml
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/loc/messages.xml?rev=1517823&r1=1517822&r2=1517823&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/loc/messages.xml (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/loc/messages.xml Tue Aug 27 14:05:03
2013
@@ -2119,6 +2119,11 @@ Guide.
             </msg>
 
             <msg>
+                <name>42X97</name>
+                <text>Conflicting constraint characteristics for constraint.</text>
+            </msg>
+
+            <msg>
                 <name>42X98</name>
                 <text>Parameters are not allowed in a VIEW definition.</text>
             </msg>
@@ -2260,6 +2265,11 @@ Guide.
             <msg>
                 <name>42XAM</name>
                 <text>The source and target tables of a MERGE statement may not have
the same correlation name.</text>
+            </msg>		
+
+	    <msg>
+                <name>42XAN</name>
+                <text>Constraint characteristics not allowed for NOT NULL.</text>
             </msg>
 
             <msg>

Modified: db/derby/code/trunk/java/shared/org/apache/derby/shared/common/reference/SQLState.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/shared/org/apache/derby/shared/common/reference/SQLState.java?rev=1517823&r1=1517822&r2=1517823&view=diff
==============================================================================
--- db/derby/code/trunk/java/shared/org/apache/derby/shared/common/reference/SQLState.java
(original)
+++ db/derby/code/trunk/java/shared/org/apache/derby/shared/common/reference/SQLState.java
Tue Aug 27 14:05:03 2013
@@ -902,7 +902,7 @@ public interface SQLState {
 	String LANG_ORDER_BY_COLUMN_NOT_FOUND                              = "42X78";
 	String LANG_DUPLICATE_COLUMN_FOR_ORDER_BY                          = "42X79";
 	String LANG_QUALIFIED_COLUMN_NAME_NOT_ALLOWED                      = "42877";
-        String LANG_UNION_ORDER_BY                                         = "42878";
+    String LANG_UNION_ORDER_BY                                         = "42878";
 	String LANG_DISTINCT_ORDER_BY                                      = "42879";
 	String LANG_DISTINCT_ORDER_BY_EXPRESSION                           = "4287A";
     String LANG_TABLE_VALUE_CTOR_RESTRICTION                           = "4287B";
@@ -911,7 +911,7 @@ public interface SQLState {
 	String LANG_USING_CARDINALITY_VIOLATION                            = "42X82";
 	String LANG_CANT_DROP_BACKING_INDEX                                = "42X84";
 	String LANG_CONSTRAINT_SCHEMA_MISMATCH                             = "42X85";
-	String LANG_DROP_NON_EXISTENT_CONSTRAINT                           = "42X86";
+    String LANG_DROP_OR_ALTER_NON_EXISTING_CONSTRAINT                  = "42X86";
 	String LANG_ALL_RESULT_EXPRESSIONS_PARAMS                          = "42X87";
 	String LANG_CONDITIONAL_NON_BOOLEAN                                = "42X88";
 	String LANG_NOT_TYPE_COMPATIBLE                                    = "42X89";
@@ -921,20 +921,21 @@ public interface SQLState {
 	String LANG_INVALID_CREATE_CONSTRAINT_COLUMN_LIST                  = "42X93";
 	String LANG_OBJECT_NOT_FOUND                                       = "42X94";
 	String LANG_DB_CLASS_PATH_HAS_MISSING_JAR                          = "42X96";
+    String LANG_INCONSISTENT_CONSTRAINT_CHARACTERISTICS                = "42X97";
 	String LANG_NO_PARAMS_IN_VIEWS                                     = "42X98";
 	String LANG_NO_PARAMS_IN_TABLES                                    = "42X99";
-    String LANG_UNASSIGNABLE_GENERATION_CLAUSE                  = "42XA0";
-    String LANG_AGGREGATE_IN_GENERATION_CLAUSE                  = "42XA1";
-    String LANG_NON_DETERMINISTIC_GENERATION_CLAUSE                  = "42XA2";
-    String LANG_CANT_OVERRIDE_GENERATION_CLAUSE                  = "42XA3";
-    String LANG_CANT_REFERENCE_GENERATED_COLUMN                  = "42XA4";
-    String LANG_ROUTINE_CANT_PERMIT_SQL                                   = "42XA5";
-    String LANG_BAD_FK_ON_GENERATED_COLUMN                           = "42XA6";
-    String LANG_GEN_COL_DEFAULT                                                 = "42XA7";
-    String LANG_GEN_COL_BAD_RENAME                                           = "42XA8";
-    String LANG_NEEDS_DATATYPE                                                      = "42XA9";
-    String LANG_GEN_COL_BEFORE_TRIG                                             = "42XAA";
-    String LANG_NOT_NULL_NEEDS_DATATYPE                                    = "42XAB";
+    String LANG_UNASSIGNABLE_GENERATION_CLAUSE                         = "42XA0";
+    String LANG_AGGREGATE_IN_GENERATION_CLAUSE                         = "42XA1";
+    String LANG_NON_DETERMINISTIC_GENERATION_CLAUSE                    = "42XA2";
+    String LANG_CANT_OVERRIDE_GENERATION_CLAUSE                        = "42XA3";
+    String LANG_CANT_REFERENCE_GENERATED_COLUMN                        = "42XA4";
+    String LANG_ROUTINE_CANT_PERMIT_SQL                                = "42XA5";
+    String LANG_BAD_FK_ON_GENERATED_COLUMN                             = "42XA6";
+    String LANG_GEN_COL_DEFAULT                                        = "42XA7";
+    String LANG_GEN_COL_BAD_RENAME                                     = "42XA8";
+    String LANG_NEEDS_DATATYPE                                         = "42XA9";
+    String LANG_GEN_COL_BEFORE_TRIG                                    = "42XAA";
+    String LANG_NOT_NULL_NEEDS_DATATYPE                                = "42XAB";
     String LANG_SEQ_INCREMENT_ZERO                                     = "42XAC";
     String LANG_SEQ_ARG_OUT_OF_DATATYPE_RANGE                          = "42XAE";
     String LANG_SEQ_MIN_EXCEEDS_MAX                                    = "42XAF";
@@ -945,9 +946,10 @@ public interface SQLState {
     String LANG_TARGET_NOT_BASE_TABLE                                  = "42XAK";    
     String LANG_SOURCE_NOT_BASE_VIEW_OR_VTI                        = "42XAL";    
     String LANG_SAME_EXPOSED_NAME                                       = "42XAM";    
+    String LANG_NOT_NULL_CHARACTERISTICS                               = "42XAN";
     String LANG_INVALID_USER_AGGREGATE_DEFINITION2                     = "42Y00";
 	String LANG_INVALID_CHECK_CONSTRAINT                               = "42Y01";
-	// String LANG_NO_ALTER_TABLE_COMPRESS_ON_TARGET_TABLE                = "42Y02";
+    // String LANG_NO_ALTER_TABLE_COMPRESS_ON_TARGET_TABLE             = "42Y02";
 	String LANG_NO_SUCH_METHOD_ALIAS                                   = "42Y03.S.0";
 	String LANG_NO_SUCH_PROCEDURE                                      = "42Y03.S.1";
 	String LANG_NO_SUCH_FUNCTION                                       = "42Y03.S.2";

Modified: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/db2Compatibility.out
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/db2Compatibility.out?rev=1517823&r1=1517822&r2=1517823&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/db2Compatibility.out
(original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/db2Compatibility.out
Tue Aug 27 14:05:03 2013
@@ -789,7 +789,7 @@ CREATE TABLE testsetconst1 (col1 CHAR(7)
 ij> CREATE TABLE testsetconst2 (col1 char(7) NOT NULL, CONSTRAINT fk FOREIGN KEY(col1)
REFERENCES testsetconst1(col1));
 0 rows inserted/updated/deleted
 ij> SET CONSTRAINTS fk DISABLED;
-ERROR 42X01: Syntax error: Encountered "CONSTRAINTS" at line 1, column 5.
+ERROR 42X01: Syntax error: Encountered "DISABLED" at line 1, column 20.
 Issue the 'help' command for general information on IJ command syntax.
 Any unrecognized commands are treated as potential SQL commands and executed directly.
 Consult your DBMS server reference documentation for details of the SQL syntax supported
by your server.
@@ -799,7 +799,7 @@ ij> SELECT STATE FROM SYS.SYSCONSTRAINTS
 E
 E
 ij> SET CONSTRAINTS fk ENABLED;
-ERROR 42X01: Syntax error: Encountered "CONSTRAINTS" at line 1, column 5.
+ERROR 42X01: Syntax error: Encountered "ENABLED" at line 1, column 20.
 Issue the 'help' command for general information on IJ command syntax.
 Any unrecognized commands are treated as potential SQL commands and executed directly.
 Consult your DBMS server reference documentation for details of the SQL syntax supported
by your server.
@@ -809,7 +809,7 @@ ij> SELECT STATE FROM SYS.SYSCONSTRAINTS
 E
 E
 ij> SET CONSTRAINTS ALL DISABLED;
-ERROR 42X01: Syntax error: Encountered "CONSTRAINTS" at line 1, column 5.
+ERROR 42X01: Syntax error: Encountered "DISABLED" at line 1, column 21.
 Issue the 'help' command for general information on IJ command syntax.
 Any unrecognized commands are treated as potential SQL commands and executed directly.
 Consult your DBMS server reference documentation for details of the SQL syntax supported
by your server.
@@ -819,7 +819,7 @@ ij> SELECT STATE FROM SYS.SYSCONSTRAINTS
 E
 E
 ij> SET CONSTRAINTS FOR testsetconst1 ENABLED;
-ERROR 42X01: Syntax error: Encountered "CONSTRAINTS" at line 1, column 5.
+ERROR 42X01: Syntax error: Encountered "FOR" at line 1, column 17.
 Issue the 'help' command for general information on IJ command syntax.
 Any unrecognized commands are treated as potential SQL commands and executed directly.
 Consult your DBMS server reference documentation for details of the SQL syntax supported
by your server.

Added: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/ConstraintCharacteristicsTest.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/ConstraintCharacteristicsTest.java?rev=1517823&view=auto
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/ConstraintCharacteristicsTest.java
(added)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/ConstraintCharacteristicsTest.java
Tue Aug 27 14:05:03 2013
@@ -0,0 +1,506 @@
+/*
+
+ Derby - Class org.apache.derbyTesting.functionTests.tests.lang.ConstraintCharacteristicsTest
+
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements.  See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ */
+
+package org.apache.derbyTesting.functionTests.tests.lang;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import static junit.framework.Assert.fail;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.derbyTesting.junit.BaseJDBCTestCase;
+import static org.apache.derbyTesting.junit.BaseJDBCTestCase.assertSQLState;
+import static org.apache.derbyTesting.junit.BaseJDBCTestCase.assertStatementError;
+import static org.apache.derbyTesting.junit.BaseJDBCTestCase.assertUpdateCount;
+import org.apache.derbyTesting.junit.JDBC;
+import org.apache.derbyTesting.junit.SystemPropertyTestSetup;
+
+public class ConstraintCharacteristicsTest extends BaseJDBCTestCase
+{
+    public ConstraintCharacteristicsTest(String name)      {
+        super(name);
+    }
+
+    public static Test suite() {
+        TestSuite suite = new TestSuite("ConstraintCharacteristicsTest");
+        suite.addTest(new ConstraintCharacteristicsTest("testSyntaxAndBinding"));
+
+        // Need to set a property to allow non default characteristics until
+        // feature completed: remove then
+        Properties systemProperties = new Properties();
+        systemProperties.setProperty("derby.constraintsTesting", "true");
+
+        TestSuite s = new TestSuite("WithLenientChecking");
+        s.addTest(new ConstraintCharacteristicsTest(
+                "testCreateConstraintDictionaryEncodings"));
+        s.addTest(new ConstraintCharacteristicsTest(
+                "testAlterConstraintDictionaryEncodings"));
+        suite.addTest(
+            new SystemPropertyTestSetup(
+                s,
+                systemProperties));
+
+        return suite;
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        createStatement().
+                executeUpdate("create table referenced(i int primary key)");
+        setAutoCommit(false);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        rollback();
+        setAutoCommit(true);
+        getConnection().createStatement().
+                executeUpdate("drop table referenced");
+        super.tearDown();
+    }
+
+    public void testSyntaxAndBinding() throws SQLException {
+        Statement s = getConnection().createStatement();
+
+        /*
+         * T A B L E    L E V E L    C O N S T R A I N T S
+         */
+
+        assertTableLevelDefaultBehaviorAccepted(s);
+        assertTableLevelFailTillFeatureImplemented(s);
+
+        /*
+         * A L T E R    C O N S T R A I N T    C H A R A C T E R I S T I C S
+         */
+        s.executeUpdate("create table t(i int, constraint app.c primary key(i))");
+
+        // default, so allow (nil action for now)
+        s.executeUpdate("alter table t alter constraint c enforced");
+
+        // not default behavior, so expect error until feature implemented
+        assertStatementError("0A000", s, "alter table t alter constraint c not enforced");
+
+        for (String ch : illegalAlterCharacteristics) {
+            // Anything beyond enforcement is illegal in ALTER context
+            assertStatementError("42X01", s, "alter table t alter constraint c " + ch);
+        }
+
+        // Unknown constraint name
+        assertStatementError("42X86", s, "alter table t alter constraint cuckoo not enforced");
+
+        /*
+         * S E T   C O N S T R A I N T
+         */
+
+        assertStatementError("0A000", s, "set constraints c deferred");
+        assertStatementError("0A000", s, "set constraints all deferred");
+
+        // Unknown constraint name
+        assertStatementError( "42X94", s, "set constraints cuckoo deferred");
+        rollback();
+
+        /*
+         * C O L U M N    L E V E L    C O N S T R A I N T S
+         */
+
+        assertColumnLevelDefaultBehaviorAccepted(s);
+        assertColumnLevelFailTillFeatureImplemented(s);
+
+        // Characteristics are not currently allowed for NOT NULL,
+        // since Derby does not represent NOT NULL as a constraint,
+        // but rather as an aspect of the column's data type. It is
+        // possible to alter the column nullable and vice versa,
+        // though.
+        assertStatementError("42XAN", s,
+                    "create table t(i int " +
+                    "not null deferrable initially immediate)");
+    }
+
+    /**
+     * Check that constraint characteristics are correctly encoded
+     * into the STATE column in SYS.SYSCONSTRAINTS.
+     * Cf. specification attached to DERBY-532.
+     *
+     * FIXME: Note that this test runs with property derby.constraintsTesting
+     * to bypass NOT IMPLEMENTED checks.  Remove this property usage when
+     * DERBY-532 is done.
+     * @throws SQLException
+     */
+    public void testCreateConstraintDictionaryEncodings() throws SQLException {
+        Statement s = getConnection().createStatement();
+
+        for (String[] ch : defaultCharacteristics) {
+            assertDictState(s, ch[0], ch[1]);
+        }
+
+        for (String[] ch : nonDefaultCharacteristics) {
+            assertDictState(s, ch[0], ch[1]);
+        }
+
+        for (String ch : illegalCharacteristics) {
+            assertCreateInconsistentCharacteristics(s, ch);
+        }
+
+        rollback();
+    }
+
+    /**
+     * Check that constraint characteristics are correctly encoded
+     * into the STATE column in SYS.SYSCONSTRAINTS.
+     * Cf. specification attached to DERBY-532.
+     *
+     * FIXME: Note that this test runs with property derby.constraintsTesting
+     * to bypass NOT IMPLEMENTED checks.  Remove this property usage when
+     * DERBY-532 is done.
+     * @throws SQLException
+     */
+    public void testAlterConstraintDictionaryEncodings() throws SQLException {
+        Statement s = getConnection().createStatement();
+
+        for (String[] ch : defaultCharacteristics) {
+            s.executeUpdate(
+                    "create table t(i int, constraint c primary key(i) " +
+                    ch[0] + ")");
+
+            assertAlterDictState(s, "enforced");
+            assertAlterDictState(s, "not enforced");
+            rollback();
+        }
+
+        for (String[] ch : nonDefaultCharacteristics) {
+            s.executeUpdate(
+                    "create table t(i int, constraint c primary key(i) " +
+                    ch[0] + ")");
+
+            assertAlterDictState(s, "enforced");
+            assertAlterDictState(s, "not enforced");
+            rollback();
+        }
+
+        for (String ch : illegalAlterCharacteristics) {
+            assertAlterInconsistentCharacteristics(s, ch);
+        }
+    }
+
+
+    private static String[] tableConstraintTypes = {
+            " foreign key (i) references referenced(i)",
+            " primary key(i)",
+            " unique(i)",
+            " check(i<3)"
+        };
+
+    private static String[] columnConstraintTypes = {
+            " references referenced(i)",
+            " primary key",
+            " unique",
+            " check(i<3)"
+        };
+
+    // Each of the three characteristics can have 3 values corresponding to
+    // {default, on, off}. This translates into 3 x 3 x 3 = 27 syntax
+    // permutations, classified below with their corresponding dictionary state.
+    //
+    private final static String[][] defaultCharacteristics = {
+        {" not deferrable initially immediate enforced", "E"},
+        {" not deferrable initially immediate", "E"},
+        {" not deferrable enforced", "E"},
+        {" not deferrable", "E"},
+        {" initially immediate enforced", "E"},
+        {" initially immediate", "E"},
+        {" enforced", "E"},
+        {"", "E"}};
+
+    private final static String[][] nonDefaultCharacteristics = {
+        {" deferrable", "i"},
+        {" deferrable initially immediate", "i"},
+        {" deferrable enforced", "i"},
+        {" deferrable initially immediate enforced", "i"},
+        {" deferrable initially deferred", "e"},
+        {" deferrable initially deferred enforced", "e"},
+        {" initially deferred enforced", "e"},
+        {" initially deferred", "e"},
+        {" deferrable not enforced", "j"},
+        {" deferrable initially immediate not enforced", "j"},
+        {" deferrable initially deferred not enforced", "d"},
+        {" initially deferred not enforced", "d"},
+        {" not enforced", "D"},
+        {" initially immediate not enforced", "D"},
+        {" not deferrable not enforced", "D"},
+        {" not deferrable initially immediate not enforced", "D"}
+    };
+
+    private final static String[] illegalCharacteristics = {
+        " not deferrable initially deferred",
+        " not deferrable initially deferred enforced",
+        " not deferrable initially deferred not enforced"
+    };
+
+    private final static String[] illegalAlterCharacteristics;
+
+    static {
+        List<String> chars = new ArrayList<String>();
+        chars.addAll(Arrays.asList(defaultCharacteristics[0]));
+        chars.addAll(Arrays.asList(nonDefaultCharacteristics[0]));
+        chars.addAll(Arrays.asList(illegalCharacteristics));
+        chars.remove(" not enforced");
+        chars.remove(" enforced");
+        chars.remove("");
+        illegalAlterCharacteristics = chars.toArray(new String[0]);
+    }
+
+    private final static Map<String, String[]> inverseState =
+            new HashMap<String, String[]>();
+
+    static {
+        inverseState.put("E", new String[]{"E", "D"});
+        inverseState.put("D", new String[]{"E", "D"});
+        inverseState.put("i", new String[]{"i", "j"});
+        inverseState.put("j", new String[]{"i", "j"});
+        inverseState.put("i", new String[]{"i", "j"});
+        inverseState.put("e", new String[]{"e", "d"});
+        inverseState.put("d", new String[]{"e", "d"});
+    }
+
+    /**
+     * Assert that we fail with feature not implemented
+     * until feature is implemented (for characteristics that are not Derby
+     * default).
+     *
+     * @param s statement
+
+     * @throws SQLException
+     */
+    private void assertTableLevelFailTillFeatureImplemented(
+            Statement s) throws SQLException {
+
+        for (String ct : tableConstraintTypes) {
+            for (String[] ch : nonDefaultCharacteristics) {
+                assertStatementError("0A000",
+                        s,
+                        "create table t(i int, constraint c " +
+                        ct + ch[0] + ")");
+            }
+        }
+    }
+
+    /**
+     * Assert that we fail with feature not implemented
+     * until feature is implemented (for characteristics that are not Derby
+     * default).
+     *
+     * @param s statement
+
+     * @throws SQLException
+     */
+    private void assertColumnLevelFailTillFeatureImplemented(
+            Statement s) throws SQLException {
+
+        for (String ct : columnConstraintTypes) {
+            for (String[] ch : nonDefaultCharacteristics) {
+                assertStatementError("0A000",
+                        s,
+                        "create table t(i int " +
+                        ct + ch[0] + ")");
+            }
+        }
+    }
+
+    /**
+     * Assert that we accept characteristics that merely specify the default
+     * behavior anyway.
+     *
+     * @param s statement
+     *
+     * @throws SQLException
+     */
+    private void assertTableLevelDefaultBehaviorAccepted (
+            Statement s) throws SQLException {
+
+        for (String ct : tableConstraintTypes) {
+            for (String[] ch : defaultCharacteristics) {
+                assertUpdateCount(
+                        s, 0,
+                        "create table t(i int, constraint c " + ct + ch[0] + ")");
+                rollback();
+            }
+        }
+    }
+
+    /**
+     * Assert that we accept characteristics that merely specify the default
+     * behavior anyway.
+     *
+     * @param s statement
+     *
+     * @throws SQLException
+     */
+    private void assertColumnLevelDefaultBehaviorAccepted (
+            Statement s) throws SQLException {
+
+        for (String ct : columnConstraintTypes) {
+            for (String ch[] : defaultCharacteristics) {
+                assertUpdateCount(
+                        s, 0,
+                        "create table t(i int " + ct + ch[0] + ")");
+                rollback();
+            }
+        }
+    }
+
+
+    /**
+     * Check that the dictionary state resulting from {@code characteristics}
+     * equals {@code}.
+     *
+     * @param characteristics  A table level constraint characteristics string
+     * @param code             Character encoding for characteristics
+     *
+     * @throws SQLException
+     */
+    private void assertFailTillFeatureImplemened(
+            Statement s,
+            String characteristics,
+            char code) throws SQLException {
+
+        for (String ct: tableConstraintTypes) {
+            s.executeUpdate("alter table alter constraint c " + ct + " " +
+                    characteristics + ")");
+
+            JDBC.assertFullResultSet(
+                s.executeQuery("select state from sys.sysconstraints " +
+                               "    where constraintname = 'C'"),
+                new String[][]{{String.valueOf(code)}});
+
+            rollback();
+        }
+    }
+
+    /**
+     * Check that the dictionary state resulting from {@code characteristics}
+     * equals {@code}.
+     *
+     * @param characteristics  A table level constraint characteristics string
+     * @param code             Character encoding for characteristics
+     *
+     * @throws SQLException
+     */
+    private void assertDictState(
+            Statement s,
+            String characteristics,
+            String code) throws SQLException {
+
+        for (String ct: tableConstraintTypes) {
+            s.executeUpdate("create table t(i int, constraint c " + ct + " " +
+                    characteristics + ")");
+
+            JDBC.assertFullResultSet(
+                s.executeQuery("select state from sys.sysconstraints " +
+                               "    where constraintname = 'C'"),
+                new String[][]{{code}});
+
+            rollback();
+        }
+    }
+
+    /**
+     * Check that the altered dictionary state resulting from new
+     * {@code characteristics} equals {@code}.
+     *
+     * @param s                The statement object to use
+     * @param enforcement  String containing ENFORCED or NOT ENFORCED
+     *
+     * @throws SQLException
+     */
+    private void assertAlterDictState(
+            Statement s,
+            String enforcement) throws SQLException {
+
+        String oldState = getOldState(s);
+        String newState = computeNewState(oldState, enforcement);
+
+        s.executeUpdate("alter table t alter constraint c " +
+                    enforcement);
+
+        JDBC.assertFullResultSet(
+                s.executeQuery("select state from sys.sysconstraints " +
+                "    where constraintname = 'C'"),
+                new String[][]{{newState}});
+    }
+
+    private String getOldState(Statement s) throws SQLException {
+        ResultSet rs = s.executeQuery(
+                "select state from sys.sysconstraints " +
+                "    where constraintname = 'C'");
+        try {
+            rs.next();
+            return rs.getString(1);
+        } finally {
+            rs.close();
+        }
+    }
+
+
+    private String computeNewState(String oldState, String enforcement) {
+        return inverseState.get(oldState)[enforcement.equals("enforced") ? 0 : 1];
+    }
+
+    private void assertCreateInconsistentCharacteristics(
+            Statement s,
+            String characteristics) throws SQLException {
+
+        for (String ct: tableConstraintTypes) {
+            try {
+                s.executeUpdate("create table t(i int, constraint c " + ct + " " +
+                        characteristics + ")");
+                fail("wrong characteristics unexpectedly passed muster");
+                rollback();
+            } catch (SQLException e) {
+                assertSQLState("42X97", e);
+            }
+        }
+    }
+
+    private void assertAlterInconsistentCharacteristics(
+            Statement s,
+            String characteristics) throws SQLException {
+
+        try {
+            s.executeUpdate("alter table t alter constraint c " +
+                    characteristics);
+            fail("wrong characteristics unexpectedly passed muster");
+            rollback();
+        } catch (SQLException e) {
+            assertSQLState("42X01", e);
+        }
+    }
+}
+

Modified: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/_Suite.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/_Suite.java?rev=1517823&r1=1517822&r2=1517823&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/_Suite.java
(original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/_Suite.java
Tue Aug 27 14:05:03 2013
@@ -241,6 +241,7 @@ public class _Suite extends BaseTestCase
         suite.addTest(NewOptimizerOverridesTest.suite());
         suite.addTest(XMLOptimizerTraceTest.suite());
         suite.addTest(MergeStatementTest.suite());
+        suite.addTest(ConstraintCharacteristicsTest.suite());
         return suite;
 	}
 }

Modified: db/derby/code/trunk/tools/ide/netbeans/nbproject/project.xml
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/tools/ide/netbeans/nbproject/project.xml?rev=1517823&r1=1517822&r2=1517823&view=diff
==============================================================================
--- db/derby/code/trunk/tools/ide/netbeans/nbproject/project.xml (original)
+++ db/derby/code/trunk/tools/ide/netbeans/nbproject/project.xml Tue Aug 27 14:05:03 2013
@@ -39,6 +39,10 @@
                     <encoding>UTF-8</encoding>
                 </source-folder>
                 <source-folder>
+                    <label>generated/java</label>
+                    <location>${project.dir}/generated/java</location>
+                </source-folder>
+                <source-folder>
                     <label>java/build</label>
                     <type>java</type>
                     <location>${project.dir}/java/build</location>
@@ -98,10 +102,6 @@
                     <location>${project.dir}/generated/java</location>
                     <encoding>UTF-8</encoding>
                 </source-folder>
-                <source-folder>
-                    <label>generated/java</label>
-                    <location>${project.dir}/generated/java</location>
-                </source-folder>
             </folders>
             <ide-actions>
                 <action name="build">



Mime
View raw message