db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From banda...@apache.org
Subject svn commit: r356133 [1/6] - in /db/derby/code/trunk/java: engine/org/apache/derby/iapi/db/ engine/org/apache/derby/iapi/reference/ engine/org/apache/derby/iapi/sql/compile/ engine/org/apache/derby/iapi/sql/conn/ engine/org/apache/derby/iapi/sql/diction...
Date Mon, 12 Dec 2005 03:58:19 GMT
Author: bandaram
Date: Sun Dec 11 19:57:33 2005
New Revision: 356133

URL: http://svn.apache.org/viewcvs?rev=356133&view=rev
Log:
DERBY-464: Submit Grant & Revoke Part I. This implements the new DDL operations along with the following:
  *  Grant/Revoke DDL parsing and execution
  *  Addition of several new system tables to hold the system metadata. I will update my spec to include detailed schema for new system tables, so that they can be included in 10.2 documentation.
  * Enhancing the syntax for routine creation to include external-security clause
  * Very simple tests to cover only the DDL. I would be expanding on the testing in the later submissions, including a JUnit test suite.
  * Grant/Revoke DDL is only supported if derby.database.defaultConnectionMode property is set to 'sqlStandard'.

Submitted by Satheesh Bandaram (satheesh@sourcery.org)

Added:
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/ColPermsDescriptor.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsCatalogRowFactory.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsDescriptor.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RequiredPermDescriptor.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RoutinePermsDescriptor.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementColumnPermission.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementPermission.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementRoutinePermission.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementTablePermission.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/TablePermsDescriptor.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/PermissionsCacheable.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/SYSCOLPERMSRowFactory.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/SYSREQUIREDPERMRowFactory.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/SYSROUTINEPERMSRowFactory.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/SYSTABLEPERMSRowFactory.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/GrantNode.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/PrivilegeNode.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/RevokeNode.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/RoutineDesignator.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/TablePrivilegesNode.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/GrantRevokeConstantAction.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/PrivilegeInfo.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/RoutinePrivilegeInfo.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/TablePrivilegeInfo.java   (with props)
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/grantRevoke.out   (with props)
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/grantRevoke.sql   (with props)
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/grantRevoke_app.properties   (with props)
Modified:
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/db/PropertyInfo.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/Property.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/SQLState.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/C_NodeTypes.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/CompilerContext.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/conn/Authorizer.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDescriptorGenerator.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDictionary.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/DataDictionaryImpl.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/C_NodeNames.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/CompilerContextImpl.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/CreateAliasNode.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/DMLModStatementNode.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/InsertNode.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/NodeFactoryImpl.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/ResultColumnList.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/ResultSetNode.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/sqlgrammar.jj
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/conn/GenericAuthorizer.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/execute/GenericConstantActionFactory.java
    db/derby/code/trunk/java/engine/org/apache/derby/loc/messages_en.properties
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/DerbyNet/metadata.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/DerbyNet/odbc_metadata.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/DerbyNet/syscat.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/DerbyNetClient/metadata.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/DerbyNetClient/odbc_metadata.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/DerbyNetClient/syscat.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/altertable.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/compressTable.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/declareGlobalTempTableJava.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/metadata.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/odbc_metadata.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/primarykey.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/syscat.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/views.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/copyfiles.ant

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/db/PropertyInfo.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/db/PropertyInfo.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/db/PropertyInfo.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/db/PropertyInfo.java Sun Dec 11 19:57:33 2005
@@ -23,6 +23,7 @@
 import org.apache.derby.iapi.error.StandardException;
 import org.apache.derby.iapi.error.PublicAPI;
 
+import org.apache.derby.iapi.sql.Activation;
 import org.apache.derby.iapi.sql.conn.Authorizer;
 import org.apache.derby.iapi.sql.conn.LanguageConnectionContext;
 import org.apache.derby.iapi.sql.conn.ConnectionUtil;

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/Property.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/Property.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/Property.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/Property.java Sun Dec 11 19:57:33 2005
@@ -524,6 +524,14 @@
 	String	LANG_TD_CACHE_SIZE = "derby.language.tableDescriptorCacheSize";
 	int		LANG_TD_CACHE_SIZE_DEFAULT = 64;
 
+    /**
+     * The size of the permissions cache used by the data dictionary.
+     * Database.  Static.
+	 * <p>
+	 * Undocumented.
+	 */
+	String	LANG_PERMISSIONS_CACHE_SIZE = "derby.language.permissionsCacheSize";
+	int		LANG_PERMISSIONS_CACHE_SIZE_DEFAULT = 64;
 	/**
 	 * The size of the stored prepared statment descriptor cache 
 	 * used by the data dictionary.  Database.  Static.
@@ -572,6 +580,7 @@
 	public static final String READ_ONLY_ACCESS = "readOnlyAccess";
 	public static final String FULL_ACCESS = "fullAccess";
 	public static final String DEFAULT_ACCESS = FULL_ACCESS;
+	public static final String SQL_STANDARD_ACCESS = "sqlStandard";
 
 	public static final String
 	READ_ONLY_ACCESS_USERS_PROPERTY = "derby.database.readOnlyAccessUsers";

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/SQLState.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/SQLState.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/SQLState.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/reference/SQLState.java Sun Dec 11 19:57:33 2005
@@ -765,8 +765,8 @@
 	String LANG_NULL_RESULT_SET_META_DATA                              = "42X43";
 	String LANG_INVALID_COLUMN_LENGTH                                  = "42X44";
 	String LANG_INVALID_FUNCTION_ARG_TYPE                              = "42X45";
-	// = "42X46";
-	// = "42X47";
+	String LANG_AMBIGUOUS_FUNCTION_NAME                                = "42X46";
+	String LANG_AMBIGUOUS_PROCEDURE_NAME                               = "42X47";
 	String LANG_INVALID_PRECISION                                      = "42X48";
 	String LANG_INVALID_INTEGER_LITERAL                                = "42X49";
 	String LANG_NO_METHOD_FOUND                                        = "42X50";
@@ -957,6 +957,8 @@
 	String LANG_GQPT_NOT_SUPPORTED									   = "42Z47.U";
 	String LANG_COLUMN_ID_ARRAY										   = "42Z48.U";
 
+	String LANG_GRANT_REVOKE_WITH_LEGACY_ACCESS                        = "42Z60";
+
 	String LANG_SERIALIZABLE										   = "42Z80.U";
 	String LANG_READ_COMMITTED										   = "42Z81.U";
 	String LANG_EXCLUSIVE											   = "42Z82.U";
@@ -1336,6 +1338,14 @@
 	String AUTH_INVALID_USER_NAME                                      = "28502.C";
 	String AUTH_USER_IN_READ_AND_WRITE_LISTS                           = "28503";
 	String AUTH_DUPLICATE_USERS                                        = "28504";
+	String AUTH_INTERNAL_BAD_UUID                                      = "28505";
+	String AUTH_NO_TABLE_PERMISSION                                    = "28506";
+	String AUTH_NO_TABLE_PERMISSION_FOR_GRANT                          = "28507";
+	String AUTH_NO_COLUMN_PERMISSION                                   = "28508";
+	String AUTH_NO_COLUMN_PERMISSION_FOR_GRANT                         = "28509";
+	String AUTH_NO_EXECUTE_PERMISSION                                  = "2850A";
+	String AUTH_NO_EXECUTE_PERMISSION_FOR_GRANT                        = "2850B";
+	String AUTH_NOT_OWNER                                              = "2850C";
 
 	/*
 	** Dependency manager

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/C_NodeTypes.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/C_NodeTypes.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/C_NodeTypes.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/C_NodeTypes.java Sun Dec 11 19:57:33 2005
@@ -115,10 +115,10 @@
 	static final int SIMPLE_STRING_OPERATOR_NODE = 83;
 	static final int STATIC_CLASS_FIELD_REFERENCE_NODE = 84;
 	static final int STATIC_METHOD_CALL_NODE = 85;
-	// 86 available
+	static final int REVOKE_NODE = 86;
 	static final int EXTRACT_OPERATOR_NODE = 87;
 	static final int PARAMETER_NODE = 88;
-	// 89 available
+	static final int GRANT_NODE = 89;
 	static final int DROP_SCHEMA_NODE = 90;
 	static final int DROP_TABLE_NODE = 91;
 	static final int DROP_VIEW_NODE = 92;
@@ -131,10 +131,10 @@
 	static final int DEFAULT_NODE = 100;
 	static final int DELETE_NODE = 101;
 	static final int UPDATE_NODE = 102;
-	// 103 is available
+	static final int PRIVILEGE_NODE = 103;
 	static final int ORDER_BY_COLUMN = 104;
 	static final int ROW_RESULT_SET_NODE = 105;
-	// 106 is available
+	static final int TABLE_PRIVILEGES_NODE = 106;
 	static final int VIRTUAL_COLUMN_NODE = 107;
 	static final int CURRENT_DATETIME_OPERATOR_NODE = 108;
 	static final int CURRENT_USER_NODE = 109; // special function CURRENT_USER

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/CompilerContext.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/CompilerContext.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/CompilerContext.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/compile/CompilerContext.java Sun Dec 11 19:57:33 2005
@@ -30,6 +30,9 @@
 
 import org.apache.derby.iapi.sql.ParameterValueSet;
 
+import org.apache.derby.iapi.sql.dictionary.AliasDescriptor;
+import org.apache.derby.iapi.sql.dictionary.ColumnDescriptor;
+import org.apache.derby.iapi.sql.dictionary.TableDescriptor;
 import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
 
 import org.apache.derby.iapi.sql.depend.Dependent;
@@ -43,6 +46,7 @@
 import org.apache.derby.iapi.store.access.StoreCostController;
 import org.apache.derby.iapi.store.access.SortCostController;
 
+import java.util.List;
 import java.util.Vector;
 import java.sql.SQLWarning;
 
@@ -511,4 +515,43 @@
 		Get the chain of compile time warnings.
 	*/
 	public SQLWarning getWarnings();
+
+	/**
+	 * Sets the current privilege type context and pushes the previous on onto a stack.
+	 * Column and table nodes do not know how they are
+	 * being used. Higher level nodes in the query tree do not know what is being
+	 * referenced. Keeping the context allows the two to come together.
+	 *
+	 * @param privType One of the privilege types in 
+	 *						org.apache.derby.iapi.sql.conn.Authorizer.
+	 */
+	public void pushCurrentPrivType( int privType);
+	
+	public void popCurrentPrivType();
+    
+	/**
+	 * Add a column privilege to the list of used column privileges.
+	 *
+	 * @param column
+	 */
+	public void addRequiredColumnPriv( ColumnDescriptor column);
+
+	/**
+	 * Add a table or view privilege to the list of used table privileges.
+	 *
+	 * @param table
+	 */
+	public void addRequiredTablePriv( TableDescriptor table);
+
+	/**
+	 * Add a routine execute privilege to the list of used routine privileges.
+	 *
+	 * @param routine
+	 */
+	public void addRequiredRoutinePriv( AliasDescriptor routine);
+
+	/**
+	 * @return The list of required privileges.
+	 */
+	public List getRequiredPermissionsList();
 }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/conn/Authorizer.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/conn/Authorizer.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/conn/Authorizer.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/conn/Authorizer.java Sun Dec 11 19:57:33 2005
@@ -20,6 +20,7 @@
 
 package org.apache.derby.iapi.sql.conn;
 
+import org.apache.derby.iapi.sql.Activation;
 import org.apache.derby.iapi.error.StandardException;
 /**
   The Authorizer verifies a connected user has the authorization 
@@ -46,15 +47,54 @@
 	/**  database jar write operation */	
 	public static final int JAR_WRITE_OP = 6;
 	
+	/* Privilege types for SQL standard (grant/revoke) permissions checking. */
+	public static final int NULL_PRIV = -1;
+	public static final int SELECT_PRIV = 0;
+	public static final int UPDATE_PRIV = 1;
+	public static final int REFERENCES_PRIV = 2;
+	public static final int INSERT_PRIV = 3;
+	public static final int DELETE_PRIV = 4;
+	public static final int TRIGGER_PRIV = 5;
+	public static final int EXECUTE_PRIV = 6;
+	public static final int PRIV_TYPE_COUNT = 7;
+
+	/**
+	 * The system authorization ID is defined by the SQL2003 spec as the grantor
+	 * of privileges to object owners.
+	 */
+	public static final String SYSTEM_AUTHORIZATION_ID = "_SYSTEM";
+
+	/**
+	 * The public authorization ID is defined by the SQL2003 spec as implying all users.
+	 */
+	public static final String PUBLIC_AUTHORIZATION_ID = "PUBLIC";
+
 	/**
 	  Verify the connected user is authorized to perform the requested
 	  operation.
 
+	  This variation should only be used with operations that do not use tables
+	  or routines. If the operation involves tables or routines then use the
+	  variation of the authorize method that takes an Activation parameter. The
+	  activation holds the table, column, and routine lists.
+
 	  @param operation the enumeration code for the requsted operation.
 
 	  @exception StandardException Thrown if the operation is not allowed
 	 */
-	public void authorize(int operation) throws StandardException;
+	public void authorize( int operation) throws StandardException;
+    
+	/**
+	  Verify the connected user is authorized to perform the requested
+	  operation.
+
+	  @param activation holds the list of tables, columns, and routines used.
+	  @param operation the enumeration code for the requsted operation.
+
+	  @exception StandardException Thrown if the operation is not allowed
+	*/
+	public void authorize(Activation activation, int operation)
+				throws StandardException;
 
     /**
 	  Get the Authorization ID for this Authorizer.
@@ -85,4 +125,12 @@
 	 @exception StandardException Oops.
 	 */
    public void refresh() throws StandardException;  
+
+	/**
+ 	  * @return true if the authorizer uses the SQL standard permissions (grant/revoke),
+	  *         false if the legacy Derby permissions system is used.
+	  *
+	  * @exception StandardException standard error policy.
+	 */
+	public boolean usesSqlStandardPermissions() throws StandardException;
 }

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/ColPermsDescriptor.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/ColPermsDescriptor.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/ColPermsDescriptor.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/ColPermsDescriptor.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,104 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.ColPermsDescriptor
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.catalog.UUID;
+
+import org.apache.derby.iapi.sql.dictionary.DataDictionary;
+import org.apache.derby.iapi.services.io.FormatableBitSet;
+
+/**
+ * This class describes a row in the SYS.SYSCOLPERMS system table, which keeps
+ * the column permissions that have been granted but not revoked.
+ */
+public class ColPermsDescriptor extends PermissionsDescriptor
+{
+    private final UUID tableUUID;
+    private final String type;
+    private final FormatableBitSet columns;
+	
+	public ColPermsDescriptor( DataDictionary dd,
+                               String grantee,
+                               String grantor,
+                               UUID tableUUID,
+                               String type,
+                               FormatableBitSet columns)
+	{
+		super (dd, grantee, grantor);
+        this.tableUUID = tableUUID;
+        this.type = type;
+        this.columns = columns;
+	}
+
+    /**
+     * This constructor just initializes the key fields of a ColPermsDescriptor
+     */
+	public ColPermsDescriptor( DataDictionary dd,
+                               String grantee,
+                               String grantor,
+                               UUID tableUUID,
+                               String type)
+    {
+        this( dd, grantee, grantor, tableUUID, type, (FormatableBitSet) null);
+    }
+    
+    public int getCatalogNumber()
+    {
+        return DataDictionary.SYSCOLPERMS_CATALOG_NUM;
+    }
+	
+	/*----- getter functions for rowfactory ------*/
+    public UUID getTableUUID() { return tableUUID;}
+    public String getType() { return type;}
+    public FormatableBitSet getColumns() { return columns;}
+
+	public String toString()
+	{
+		return "colPerms: grantor=" + getGrantee() + 
+			",grantor=" + getGrantor() +
+          ",tableUUID=" + getTableUUID() +
+          ",type=" + getType() +
+          ",columns=" + getColumns();
+	}		
+
+    /**
+     * @return true iff the key part of this permissions descriptor equals the key part of another permissions
+     *         descriptor.
+     */
+    public boolean equals( Object other)
+    {
+        if( !( other instanceof ColPermsDescriptor))
+            return false;
+        ColPermsDescriptor otherColPerms = (ColPermsDescriptor) other;
+        return super.keyEquals( otherColPerms) &&
+          tableUUID.equals( otherColPerms.tableUUID) &&
+          ((type == null) ? (otherColPerms.type == null) : type.equals( otherColPerms.type));
+    }
+    
+    /**
+     * @return the hashCode for the key part of this permissions descriptor
+     */
+    public int hashCode()
+    {
+        return super.keyHashCode() + tableUUID.hashCode() +
+          ((type == null) ? 0 : type.hashCode());
+    }
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/ColPermsDescriptor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDescriptorGenerator.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDescriptorGenerator.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDescriptorGenerator.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDescriptorGenerator.java Sun Dec 11 19:57:33 2005
@@ -32,6 +32,7 @@
 import org.apache.derby.iapi.sql.execute.ConstantAction;
 import org.apache.derby.iapi.sql.execute.ExecPreparedStatement;
 import org.apache.derby.iapi.services.uuid.UUIDFactory;
+import org.apache.derby.iapi.services.io.FormatableBitSet;
 
 import org.apache.derby.catalog.AliasInfo;
 import org.apache.derby.catalog.DefaultInfo;
@@ -431,4 +432,70 @@
 		return new FileInfoDescriptor(dataDictionary, id,sd,SQLName,generationId);
 	}
 	 	
+    public TablePermsDescriptor newTablePermsDescriptor( TableDescriptor td,
+                                                         String selectPerm,
+                                                         String deletePerm,
+                                                         String insertPerm,
+                                                         String updatePerm,
+                                                         String referencesPerm,
+                                                         String triggerPerm,
+                                                         String grantor)
+    {
+        if( "N".equals( selectPerm) && "N".equals( deletePerm) && "N".equals( insertPerm)
+            && "N".equals( updatePerm) && "N".equals( referencesPerm) && "N".equals( triggerPerm))
+            return null;
+        
+        return new TablePermsDescriptor( dataDictionary,
+                                         (String) null,
+                                         grantor,
+                                         td.getUUID(),
+                                         selectPerm,
+                                         deletePerm,
+                                         insertPerm,
+                                         updatePerm,
+                                         referencesPerm,
+                                         triggerPerm);
+    }
+
+    /**
+     * Manufacture a new ColPermsDescriptor.
+     *
+     * @param td The descriptor of the table.
+     * @param type The action type:
+     *<ol>
+     *<li>"s" - select without grant
+     *<li>"S" - select with grant
+     *<li>"u" - update without grant
+     *<li>"U" - update with grant
+     *<li>"r" - references without grant
+     *<li>"R" - references with grant
+     *</ol>
+     * @param columns the set of columns
+     */
+    public ColPermsDescriptor newColPermsDescriptor( TableDescriptor td,
+                                                     String type,
+                                                     FormatableBitSet columns,
+                                                     String grantor)
+    {
+        return new ColPermsDescriptor( dataDictionary,
+                                       (String) null,
+                                       grantor,
+                                       td.getUUID(),
+                                       type,
+                                       columns);
+    }
+
+    /**
+     * Create a new routine permissions descriptor
+     *
+     * @param ad The routine's alias descriptor
+     * @param grantor
+     */
+    public RoutinePermsDescriptor newRoutinePermsDescriptor( AliasDescriptor ad, String grantor)
+    {
+        return new RoutinePermsDescriptor( dataDictionary,
+                                           (String) null,
+                                           grantor,
+                                           ad.getUUID());
+    }
 }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDictionary.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDictionary.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDictionary.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/DataDictionary.java Sun Dec 11 19:57:33 2005
@@ -42,7 +42,6 @@
 import org.apache.derby.iapi.services.uuid.UUIDFactory;
 
 import java.util.List;
-
 import java.util.Hashtable;
 import java.util.Properties;
 import java.util.Vector;
@@ -131,6 +130,10 @@
 	public static final int SYSTRIGGERS_CATALOG_NUM = 13;
 	public static final int SYSSTATISTICS_CATALOG_NUM = 14;    
 	public static final int SYSDUMMY1_CATALOG_NUM = 15;
+	public static final int SYSTABLEPERMS_CATALOG_NUM = 16;
+	public static final int SYSCOLPERMS_CATALOG_NUM = 17;
+	public static final int SYSROUTINEPERMS_CATALOG_NUM = 18;
+	public static final int SYSREQUIREDPERM_CATALOG_NUM = 19;
 
 	/* static finals for constraints 
 	 * (Here because they are needed by parser, compilation and execution.)
@@ -679,7 +682,7 @@
 	/**
 	 * Return a table descriptor corresponding to the TABLEID
 	 * field in SYSCONSTRAINTS where CONSTRAINTID matches
-	 * the constraintId passsed in.
+	 * the constraintId passed in.
 	 *
 	 * @param constraintId	The id of the constraint
 	 *
@@ -1539,6 +1542,69 @@
 	*/
 	public boolean checkVersion(int majorVersion, String feature) throws StandardException;
 	
+    /**
+     * Add or remove a permission to the permission database.
+     *
+     * @param add if true then add the permission, if false remove it.
+     * @param perm
+     * @param grantee
+     * @param tc
+     *
+     */
+    public void addRemovePermissionsDescriptor( boolean add,
+                                                 PermissionsDescriptor perm,
+                                                 String grantee,
+                                                 TransactionController tc)
+        throws StandardException;
+
+    /**
+     * Get one user's privileges on a table
+     *
+     * @param tableUUID
+     * @param authorizationId The user name
+     *
+     * @return a TablePermsDescriptor or null if the user has no permissions on the table.
+     *
+     * @exception StandardException
+     */
+    public TablePermsDescriptor getTablePermissions( UUID tableUUID, String authorizationId)
+        throws StandardException;
+
+    /**
+     * Get one user's column privileges for a table.
+     *
+     * @param tableUUID
+     * @param privType Authorizer.SELECT_PRIV, Authorizer.UPDATE_PRIV, or Authorizer.REFERENCES_PRIV
+     * @param forGrant
+     * @param authorizationId The user name
+     *
+     * @return a ColPermsDescriptor or null if the user has no separate column
+     *         permissions of the specified type on the table. Note that the user may have been granted
+     *         permission on all the columns of the table (no column list), in which case this routine
+     *         will return null. You must also call getTablePermissions to see if the user has permission
+     *         on a set of columns.
+     *
+     * @exception StandardException
+     */
+    public ColPermsDescriptor getColumnPermissions( UUID tableUUID,
+                                                    int privType,
+                                                    boolean forGrant,
+                                                    String authorizationId)
+        throws StandardException;
+
+    /**
+     * Get one user's permissions for a routine (function or procedure).
+     *
+     * @param routineUUID
+     * @param authorizationId The user's name
+     *
+     * @return The descriptor of the users permissions for the routine.
+     *
+     * @exception StandardException
+     */
+    public RoutinePermsDescriptor getRoutinePermissions( UUID routineUUID, String authorizationId)
+        throws StandardException;
+
 	/**
 	 * Return the Java class to use for the VTI for
 	 * the virtual table. Assumes the descriptor is

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsCatalogRowFactory.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsCatalogRowFactory.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsCatalogRowFactory.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsCatalogRowFactory.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,118 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.PermissionsCatalogRowFactory
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.iapi.error.StandardException;
+import org.apache.derby.iapi.reference.Limits;
+import org.apache.derby.iapi.services.uuid.UUIDFactory;
+import org.apache.derby.iapi.sql.dictionary.PermissionsDescriptor;
+import org.apache.derby.iapi.sql.execute.ExecIndexRow;
+import org.apache.derby.iapi.sql.execute.ExecRow;
+import org.apache.derby.iapi.sql.execute.ExecutionFactory;
+import org.apache.derby.iapi.types.DataValueDescriptor;
+import org.apache.derby.iapi.types.DataValueFactory;
+import org.apache.derby.iapi.types.RowLocation;
+import org.apache.derby.iapi.types.StringDataValue;
+
+public abstract class PermissionsCatalogRowFactory extends CatalogRowFactory
+{
+    public static final String AUTHORIZATION_ID_TYPE = "VARCHAR";
+    public static final boolean AUTHORIZATION_ID_IS_BUILTIN_TYPE = true;
+    public static final int AUTHORIZATION_ID_LENGTH = Limits.DB2_MAX_USERID_LENGTH;
+
+    public PermissionsCatalogRowFactory(UUIDFactory uuidf, ExecutionFactory ef, DataValueFactory dvf,
+                                        boolean convertIdToLower)
+    {
+        super(uuidf,ef,dvf,convertIdToLower);
+    }
+
+    protected DataValueDescriptor getAuthorizationID( String value)
+    {
+        return getDataValueFactory().getVarcharDataValue( value);
+    }
+
+    protected DataValueDescriptor getNullAuthorizationID()
+    {
+        return getDataValueFactory().getNullVarchar( (StringDataValue) null);
+    }
+
+    /**
+     * Extract an internal authorization ID from a row.
+     *
+     * @param row
+     * @param columnPos 1 based
+     *
+     * @return The internal authorization ID
+     */
+    protected String getAuthorizationID( ExecRow row, int columnPos)
+        throws StandardException
+    {
+        return row.getColumn( columnPos).getString();
+    }
+    
+    /**
+     * @return the index number of the primary key index.
+     */
+    public abstract int getPrimaryIndexNumber();
+
+    /**
+     * Build an index key row from a permission descriptor. A key row does not include the RowLocation column.
+     *
+     * @param indexNumber
+     * @param perm a permission descriptor of the appropriate class for this PermissionsCatalogRowFactory class.
+     * @param rowLocation
+     *
+     * @exception StandardException standard error policy
+     */
+    public abstract ExecIndexRow buildIndexKeyRow( int indexNumber,
+                                                   PermissionsDescriptor perm)
+        throws StandardException;
+
+    /**
+     * Or a set of permissions in with a row from this catalog table
+     *
+     * @param row an existing row
+     * @param perm a permission descriptor of the appropriate class for this PermissionsCatalogRowFactory class.
+     * @param colsChanged An array with one element for each column in row. It is updated to
+     *                    indicate which columns in row were changed
+     *
+     * @return The number of columns that were changed.
+     *
+     * @exception StandardException standard error policy
+     */
+    abstract public int orPermissions( ExecRow row, PermissionsDescriptor perm, boolean[] colsChanged)
+        throws StandardException;
+
+    /**
+     * Remove a set of permissions from a row from this catalog table
+     *
+     * @param row an existing row
+     * @param perm a permission descriptor of the appropriate class for this PermissionsCatalogRowFactory class.
+     * @param colsChanged An array with one element for each column in row. It is updated to
+     *                    indicate which columns in row were changed
+     *
+     * @return -1 if there are no permissions left in the row, otherwise the number of columns that were changed.
+     *
+     * @exception StandardException standard error policy
+     */
+    abstract public int removePermissions( ExecRow row, PermissionsDescriptor perm, boolean[] colsChanged)
+        throws StandardException;
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsCatalogRowFactory.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsDescriptor.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsDescriptor.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsDescriptor.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsDescriptor.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,85 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.PermissionsDescriptor
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.iapi.sql.dictionary.DataDictionary;
+import org.apache.derby.iapi.services.sanity.SanityManager;
+
+/**
+ * This class is used by rows in the SYS.SYSTABLEPERMS, SYS.SYSCOLPERMS, and SYS.SYSROUTINEPERMS
+ * system tables.
+ */
+public abstract class PermissionsDescriptor extends TupleDescriptor implements Cloneable
+{
+	protected String grantee;
+	protected String grantor;
+
+	public PermissionsDescriptor( DataDictionary dd,
+								  String grantee,
+								  String grantor)
+	{
+		super (dd);
+		this.grantee = grantee;
+		this.grantor = grantor;
+	}
+
+	public Object clone()
+	{
+		try
+		{
+			return super.clone();
+		}
+		catch( java.lang.CloneNotSupportedException cnse)
+		{
+			if( SanityManager.DEBUG)
+				SanityManager.THROWASSERT( "Could not clone a " + getClass().getName());
+			return null;
+		}
+	}
+	
+	public abstract int getCatalogNumber();
+
+	/**
+	 * @return true iff the key part of this permissions descriptor equals the key part of another permissions
+	 *		 descriptor.
+	 */
+	protected boolean keyEquals( PermissionsDescriptor other)
+	{
+		return grantee.equals( other.grantee);
+	}
+		   
+	/**
+	 * @return the hashCode for the key part of this permissions descriptor
+	 */
+	protected int keyHashCode()
+	{
+		return grantee.hashCode();
+	}
+	
+	public void setGrantee( String grantee)
+	{
+		this.grantee = grantee;
+	}
+	
+	/*----- getter functions for rowfactory ------*/
+	public String getGrantee() { return grantee;}
+	public String getGrantor() { return grantor;}
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/PermissionsDescriptor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RequiredPermDescriptor.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RequiredPermDescriptor.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RequiredPermDescriptor.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RequiredPermDescriptor.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,69 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.RequiredPermDescriptor
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.catalog.UUID;
+
+import org.apache.derby.iapi.sql.dictionary.DataDictionary;
+import org.apache.derby.iapi.services.io.FormatableBitSet;
+
+/**
+ * This class implements a row in the SYS.SYSREQUIREDPERM table, which keeps
+ * track of the permissions required by views, triggers, and constraints.
+ *
+ */
+public class RequiredPermDescriptor extends TupleDescriptor
+{
+	private UUID operatorUUID;
+	private String operatorType;
+	private String permType;
+	private UUID objectUUID;
+	private FormatableBitSet columns;
+	
+	public RequiredPermDescriptor( UUID operatorUUID,
+								   String operatorType,
+								   String permType,
+								   UUID objectUUID,
+								   FormatableBitSet columns)
+	{
+		this.operatorUUID = operatorUUID;
+		this.operatorType = operatorType;
+		this.permType = permType;
+		this.objectUUID = objectUUID;
+		this.columns = columns;
+	}
+	
+	/*----- getter functions for rowfactory ------*/
+	public UUID getOperatorUUID() { return operatorUUID;}
+	public String getOperatorType() { return operatorType;}
+	public String getPermType() { return permType;}
+	public UUID getObjectUUID() { return objectUUID;}
+	public FormatableBitSet getColumns() { return columns;}
+
+	public String toString()
+	{
+		return "RequiredPerm: operatorUUID=" + getOperatorUUID() + 
+			",operatortype=" + getOperatorType() +
+		  ",permtype=" + getPermType() +
+		  ",objectUUID=" + getObjectUUID() +
+		  ",columns=" + getColumns();
+	}		
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RequiredPermDescriptor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RoutinePermsDescriptor.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RoutinePermsDescriptor.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RoutinePermsDescriptor.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RoutinePermsDescriptor.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,101 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.RoutinePermsDescriptor
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.catalog.UUID;
+
+import org.apache.derby.iapi.sql.dictionary.DataDictionary;
+
+/**
+ * This class describes rows in the SYS.SYSROUTINEPERMS system table, which keeps track of the routine
+ * (procedure and function) permissions that have been granted but not revoked.
+ */
+public class RoutinePermsDescriptor extends PermissionsDescriptor
+{
+    private final UUID routineUUID;
+    private final boolean hasExecutePermission;
+	
+	public RoutinePermsDescriptor( DataDictionary dd,
+                                   String grantee,
+                                   String grantor,
+                                   UUID routineUUID,
+                                   boolean hasExecutePermission)
+	{
+		super (dd, grantor, grantee);
+        this.routineUUID = routineUUID;
+        this.hasExecutePermission = hasExecutePermission;
+	}
+	
+	public RoutinePermsDescriptor( DataDictionary dd,
+                                   String grantee,
+                                   String grantor,
+                                   UUID routineUUID)
+	{
+        this( dd, grantor, grantee, routineUUID, true);
+	}
+
+    /**
+     * This constructor just sets up the key fields of a RoutinePermsDescriptor.
+     */
+	public RoutinePermsDescriptor( DataDictionary dd,
+                                   String grantee,
+                                   String grantor)
+    {
+        this( dd, grantee, grantor, (UUID) null);
+    }
+    
+    public int getCatalogNumber()
+    {
+        return DataDictionary.SYSROUTINEPERMS_CATALOG_NUM;
+    }
+	
+	/*----- getter functions for rowfactory ------*/
+    public UUID getRoutineUUID() { return routineUUID;}
+    public boolean getHasExecutePermission() { return hasExecutePermission;}
+
+	public String toString()
+	{
+		return "routinePerms: grantor=" + getGrantee() + 
+          ",grantor=" + getGrantor() +
+          ",routineUUID=" + getRoutineUUID();
+	}		
+
+    /**
+     * @return true iff the key part of this permissions descriptor equals the key part of another permissions
+     *         descriptor.
+     */
+    public boolean equals( Object other)
+    {
+        if( !( other instanceof RoutinePermsDescriptor))
+            return false;
+        RoutinePermsDescriptor otherRoutinePerms = (RoutinePermsDescriptor) other;
+        return super.keyEquals( otherRoutinePerms) &&
+          routineUUID.equals( otherRoutinePerms.routineUUID);
+    }
+    
+    /**
+     * @return the hashCode for the key part of this permissions descriptor
+     */
+    public int hashCode()
+    {
+        return super.keyHashCode() + routineUUID.hashCode();
+    }
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/RoutinePermsDescriptor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementColumnPermission.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementColumnPermission.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementColumnPermission.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementColumnPermission.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,140 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.StatementColumnPermission
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.iapi.error.StandardException;
+import org.apache.derby.catalog.UUID;
+import org.apache.derby.iapi.sql.conn.Authorizer;
+import org.apache.derby.iapi.reference.SQLState;
+import org.apache.derby.iapi.services.io.FormatableBitSet;
+import org.apache.derby.iapi.store.access.TransactionController;
+
+/**
+ * This class describes a columnpermission used (required) by a statement.
+ */
+
+public class StatementColumnPermission extends StatementTablePermission
+{
+	private FormatableBitSet columns;
+
+	public StatementColumnPermission( UUID tableUUID, int privType, FormatableBitSet columns)
+	{
+		super( tableUUID, privType);
+		this.columns = columns;
+	}
+
+	public FormatableBitSet getColumns()
+	{
+		return columns;
+	}
+
+	public boolean equals( Object obj)
+	{
+		if( obj instanceof StatementColumnPermission)
+		{
+			StatementColumnPermission other = (StatementColumnPermission) obj;
+			if( ! columns.equals( other.columns))
+				return false;
+			return super.equals( obj);
+		}
+		return false;
+	}
+	
+	/**
+	 * @param tc the TransactionController
+	 * @param dd A DataDictionary
+	 * @param authorizationId A user
+	 * @param forGrant
+	 *
+	 * @exception StandardException if the permission has not been granted
+	 */
+	public void check( TransactionController tc,
+					   DataDictionary dd,
+					   String authorizationId,
+					   boolean forGrant)
+		throws StandardException
+	{
+		if( hasPermissionOnTable(dd, authorizationId, forGrant))
+			return;
+		FormatableBitSet permittedColumns = null;
+		FormatableBitSet grantablePermittedColumns = null;
+		FormatableBitSet publicPermittedColumns = null;
+		FormatableBitSet publicPrantablePermittedColumns = null;
+		if( ! forGrant)
+		{
+			permittedColumns = addPermittedColumns( dd,
+													false /* non-grantable permissions */,
+													Authorizer.PUBLIC_AUTHORIZATION_ID,
+													permittedColumns);
+			permittedColumns = addPermittedColumns( dd,
+													false /* non-grantable permissions */,
+													authorizationId,
+													permittedColumns);
+		}
+		permittedColumns = addPermittedColumns( dd,
+												true /* grantable permissions */,
+												Authorizer.PUBLIC_AUTHORIZATION_ID,
+												permittedColumns);
+		permittedColumns = addPermittedColumns( dd,
+												true /* grantable permissions */,
+												authorizationId,
+												permittedColumns);
+												
+		for( int i = columns.anySetBit(); i >= 0; i = columns.anySetBit( i))
+		{
+			if( permittedColumns != null && permittedColumns.get(i))
+				continue;
+			// No permission on this column.
+			TableDescriptor td = getTableDescriptor( dd);
+			ColumnDescriptor cd = td.getColumnDescriptor( i + 1);
+			if( cd == null)
+				throw StandardException.newException( SQLState.AUTH_INTERNAL_BAD_UUID, "column");
+			throw StandardException.newException( forGrant ? SQLState.AUTH_NO_COLUMN_PERMISSION_FOR_GRANT
+												  : SQLState.AUTH_NO_COLUMN_PERMISSION,
+												  authorizationId,
+												  getPrivName(),
+												  cd.getColumnName(),
+												  td.getSchemaName(),
+												  td.getName());
+		}
+	} // end of check
+
+	/**
+	 * Add one user's set of permitted columns to a list of permitted columns.
+	 */
+	private FormatableBitSet addPermittedColumns( DataDictionary dd,
+												  boolean forGrant,
+												  String authorizationId,
+												  FormatableBitSet permittedColumns)
+		throws StandardException
+	{
+		if( permittedColumns != null && permittedColumns.getNumBitsSet() == permittedColumns.size())
+			return permittedColumns;
+		ColPermsDescriptor perms = dd.getColumnPermissions( tableUUID, privType, false, authorizationId);
+		if( perms != null)
+		{
+			if( permittedColumns == null)
+				return perms.getColumns();
+			permittedColumns.or( perms.getColumns());
+		}
+		return permittedColumns;
+	} // end of addPermittedColumns
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementColumnPermission.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementPermission.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementPermission.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementPermission.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementPermission.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,44 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.StatementPermission
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.iapi.store.access.TransactionController;
+import org.apache.derby.iapi.error.StandardException;
+
+/**
+ * This class describes a permission used (required) by a statement.
+ */
+
+public abstract class StatementPermission
+{
+	/**
+	 * @param tc the TransactionController
+	 * @param dd A DataDictionary
+	 * @param authorizationId A user
+	 * @param forGrant
+	 *
+	 * @exception StandardException if the permission has not been granted
+	 */
+	public abstract void check( TransactionController tc,
+								DataDictionary dd,
+								String authorizationId,
+								boolean forGrant) throws StandardException;
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementPermission.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementRoutinePermission.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementRoutinePermission.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementRoutinePermission.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementRoutinePermission.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,74 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.StatementRoutinePermission
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.iapi.error.StandardException;
+import org.apache.derby.catalog.UUID;
+import org.apache.derby.iapi.sql.conn.Authorizer;
+import org.apache.derby.iapi.reference.SQLState;
+import org.apache.derby.iapi.sql.dictionary.RoutinePermsDescriptor;
+import org.apache.derby.iapi.store.access.TransactionController;
+
+/**
+ * This class describes a routine permission used (required) by a statement.
+ */
+
+public class StatementRoutinePermission extends StatementPermission
+{
+	protected UUID routineUUID;
+
+	public StatementRoutinePermission( UUID routineUUID)
+	{
+		this.routineUUID = routineUUID;
+	}
+									 
+	/**
+	 * @param tc the TransactionController
+	 * @param dd A DataDictionary
+	 * @param authorizationId A user
+	 * @param forGrant
+	 *
+	 * @exception StandardException if the permission has not been granted
+	 */
+	public void check( TransactionController tc,
+					   DataDictionary dd,
+					   String authorizationId,
+					   boolean forGrant) throws StandardException
+	{
+		RoutinePermsDescriptor perms = dd.getRoutinePermissions( routineUUID, authorizationId);
+		if( perms == null || ! perms.getHasExecutePermission())
+		{
+			AliasDescriptor ad = dd.getAliasDescriptor( routineUUID);
+			if( ad == null)
+				throw StandardException.newException( SQLState.AUTH_INTERNAL_BAD_UUID, "routine");
+			SchemaDescriptor sd = dd.getSchemaDescriptor( ad.getSchemaUUID(), tc);
+			if( sd == null)
+				throw StandardException.newException( SQLState.AUTH_INTERNAL_BAD_UUID, "schema");
+			throw StandardException.newException( forGrant ? SQLState.AUTH_NO_EXECUTE_PERMISSION_FOR_GRANT
+												  : SQLState.AUTH_NO_EXECUTE_PERMISSION,
+												  authorizationId,
+												  ad.getDescriptorType(),
+												  sd.getSchemaName(),
+												  ad.getDescriptorName());
+		}
+	} // end of check
+
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementRoutinePermission.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementTablePermission.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementTablePermission.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementTablePermission.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementTablePermission.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,165 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.StatementTablePermission
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.iapi.error.StandardException;
+import org.apache.derby.catalog.UUID;
+import org.apache.derby.iapi.sql.conn.Authorizer;
+import org.apache.derby.iapi.reference.SQLState;
+import org.apache.derby.iapi.store.access.TransactionController;
+
+/**
+ * This class describes a table permission used (required) by a statement.
+ */
+
+public class StatementTablePermission extends StatementPermission
+{
+	protected UUID tableUUID;
+	protected int privType; // One of Authorizer.SELECT_PRIV, UPDATE_PRIV, etc.
+
+	public StatementTablePermission( UUID tableUUID, int privType)
+	{
+		this.tableUUID = tableUUID;
+		this.privType = privType;
+	}
+
+	public int getPrivType()
+	{
+		return privType;
+	}
+
+	public UUID getTableUUID()
+	{
+		return tableUUID;
+	}
+
+	public boolean equals( Object obj)
+	{
+		if( obj == null)
+			return false;
+		if( getClass().equals( obj.getClass()))
+		{
+			StatementTablePermission other = (StatementTablePermission) obj;
+			return privType == other.privType && tableUUID.equals( other.tableUUID);
+		}
+		return false;
+	} // end of equals
+
+	public int hashCode()
+	{
+		return privType + tableUUID.hashCode();
+	}
+	
+	/**
+	 * @param tc the TransactionController
+	 * @param dd A DataDictionary
+	 * @param authorizationId A user
+	 * @param forGrant
+	 *
+	 * @exception StandardException if the permission has not been granted
+	 */
+	public void check( TransactionController tc,
+					   DataDictionary dd,
+					   String authorizationId,
+					   boolean forGrant)
+		throws StandardException
+	{
+		if( ! hasPermissionOnTable( dd, authorizationId, forGrant))
+		{
+			TableDescriptor td = getTableDescriptor( dd);
+			throw StandardException.newException( forGrant ? SQLState.AUTH_NO_TABLE_PERMISSION_FOR_GRANT
+												  : SQLState.AUTH_NO_TABLE_PERMISSION,
+												  authorizationId,
+												  getPrivName(),
+												  td.getSchemaName(),
+												  td.getName());
+		}
+	} // end of check
+
+	protected TableDescriptor getTableDescriptor( DataDictionary dd)  throws StandardException
+	{
+		TableDescriptor td = dd.getTableDescriptor( tableUUID);
+		if( td == null)
+			throw StandardException.newException( SQLState.AUTH_INTERNAL_BAD_UUID, "table");
+		return td;
+	} // end of getTableDescriptor
+
+	protected boolean hasPermissionOnTable( DataDictionary dd, String authorizationId, boolean forGrant)
+		throws StandardException
+	{
+		return oneAuthHasPermissionOnTable( dd, Authorizer.PUBLIC_AUTHORIZATION_ID, forGrant)
+		  || oneAuthHasPermissionOnTable( dd, authorizationId, forGrant);
+	}
+
+	private boolean oneAuthHasPermissionOnTable( DataDictionary dd, String authorizationId, boolean forGrant)
+		throws StandardException
+	{
+		TablePermsDescriptor perms = dd.getTablePermissions( tableUUID, authorizationId);
+		if( perms == null)
+			return false;
+		
+		String priv = null;
+			
+		switch( privType)
+		{
+		case Authorizer.SELECT_PRIV:
+			priv = perms.getSelectPriv();
+			break;
+		case Authorizer.UPDATE_PRIV:
+			priv = perms.getUpdatePriv();
+			break;
+		case Authorizer.REFERENCES_PRIV:
+			priv = perms.getReferencesPriv();
+			break;
+		case Authorizer.INSERT_PRIV:
+			priv = perms.getInsertPriv();
+			break;
+		case Authorizer.DELETE_PRIV:
+			priv = perms.getDeletePriv();
+			break;
+		case Authorizer.TRIGGER_PRIV:
+			priv = perms.getTriggerPriv();
+			break;
+		}
+
+		return "Y".equals(priv) || (!forGrant) && "y".equals( priv);
+	} // end of hasPermissionOnTable
+
+	public String getPrivName( )
+	{
+		switch( privType)
+		{
+		case Authorizer.SELECT_PRIV:
+			return "select";
+		case Authorizer.UPDATE_PRIV:
+			return "update";
+		case Authorizer.REFERENCES_PRIV:
+			return "references";
+		case Authorizer.INSERT_PRIV:
+			return "insert";
+		case Authorizer.DELETE_PRIV:
+			return "delete";
+		case Authorizer.TRIGGER_PRIV:
+			return "trigger";
+		}
+		return "?";
+	} // end of getPrivName
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/StatementTablePermission.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/TablePermsDescriptor.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/TablePermsDescriptor.java?rev=356133&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/TablePermsDescriptor.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/TablePermsDescriptor.java Sun Dec 11 19:57:33 2005
@@ -0,0 +1,120 @@
+/*
+
+   Derby - Class org.apache.derby.iapi.sql.dictionary.TablePermsDescriptor
+
+   Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+
+   Licensed 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.derby.iapi.sql.dictionary;
+
+import org.apache.derby.catalog.UUID;
+
+import org.apache.derby.iapi.sql.dictionary.DataDictionary;
+
+/**
+ * This class describes a row in the SYS.SYSTABLEPERMS system table, which
+ * stores the table permissions that have been granted but not revoked.
+ */
+public class TablePermsDescriptor extends PermissionsDescriptor
+{
+    private final UUID tableUUID;
+    private final String selectPriv;
+    private final String deletePriv;
+    private final String insertPriv;
+    private final String updatePriv;
+    private final String referencesPriv;
+    private final String triggerPriv;
+	
+	public TablePermsDescriptor( DataDictionary dd,
+                                 String grantee,
+                                 String grantor,
+                                 UUID tableUUID,
+                                 String selectPriv,
+                                 String deletePriv,
+                                 String insertPriv,
+                                 String updatePriv,
+                                 String referencesPriv,
+                                 String triggerPriv)
+	{
+		super (dd, grantee, grantor);
+        this.tableUUID = tableUUID;
+        this.selectPriv = selectPriv;
+        this.deletePriv = deletePriv;
+        this.insertPriv = insertPriv;
+        this.updatePriv = updatePriv;
+        this.referencesPriv = referencesPriv;
+        this.triggerPriv = triggerPriv;
+	}
+
+    /**
+     * This constructor just sets up the key fields of a TablePermsDescriptor
+     */
+    public TablePermsDescriptor( DataDictionary dd,
+                                 String grantee,
+                                 String grantor,
+                                 UUID tableUUID)
+    {
+        this( dd, grantee, grantor, tableUUID,
+              (String) null, (String) null, (String) null, (String) null, (String) null, (String) null);
+    }
+    
+    public int getCatalogNumber()
+    {
+        return DataDictionary.SYSTABLEPERMS_CATALOG_NUM;
+    }
+	
+	/*----- getter functions for rowfactory ------*/
+    public UUID getTableUUID() { return tableUUID;}
+    public String getSelectPriv() { return selectPriv;}
+    public String getDeletePriv() { return deletePriv;}
+    public String getInsertPriv() { return insertPriv;}
+    public String getUpdatePriv() { return updatePriv;}
+    public String getReferencesPriv() { return referencesPriv;}
+    public String getTriggerPriv() { return triggerPriv;}
+
+	public String toString()
+	{
+		return "tablePerms: grantee=" + getGrantee() + 
+			",grantor=" + getGrantor() +
+          ",tableUUID=" + getTableUUID() +
+          ",selectPriv=" + getSelectPriv() +
+          ",deletePriv=" + getDeletePriv() +
+          ",insertPriv=" + getInsertPriv() +
+          ",updatePriv=" + getUpdatePriv() +
+          ",referencesPriv=" + getReferencesPriv() +
+          ",triggerPriv=" + getTriggerPriv();
+	}
+
+    /**
+     * @return true iff the key part of this permissions descriptor equals the key part of another permissions
+     *         descriptor.
+     */
+    public boolean equals( Object other)
+    {
+        if( !( other instanceof TablePermsDescriptor))
+            return false;
+        TablePermsDescriptor otherTablePerms = (TablePermsDescriptor) other;
+        return super.keyEquals( otherTablePerms) && tableUUID.equals( otherTablePerms.tableUUID);
+    }
+    
+    /**
+     * @return the hashCode for the key part of this permissions descriptor
+     */
+    public int hashCode()
+    {
+        return super.keyHashCode() + tableUUID.hashCode();
+    }
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/iapi/sql/dictionary/TablePermsDescriptor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/DataDictionaryImpl.java
URL: http://svn.apache.org/viewcvs/db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/DataDictionaryImpl.java?rev=356133&r1=356132&r2=356133&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/DataDictionaryImpl.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/catalog/DataDictionaryImpl.java Sun Dec 11 19:57:33 2005
@@ -24,9 +24,11 @@
 import org.apache.derby.iapi.reference.Property;
 import org.apache.derby.iapi.reference.SQLState;
 import org.apache.derby.iapi.reference.Limits;
+import org.apache.derby.iapi.sql.conn.Authorizer;
 
 import org.apache.derby.iapi.sql.dictionary.AliasDescriptor;
 import org.apache.derby.iapi.sql.dictionary.CatalogRowFactory;
+import org.apache.derby.iapi.sql.dictionary.PermissionsCatalogRowFactory;
 
 import org.apache.derby.iapi.sql.dictionary.ColumnDescriptor;
 import org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList;
@@ -45,6 +47,10 @@
 import org.apache.derby.iapi.sql.dictionary.TupleDescriptor;
 import org.apache.derby.iapi.sql.dictionary.IndexRowGenerator;
 import org.apache.derby.iapi.sql.dictionary.KeyConstraintDescriptor;
+import org.apache.derby.iapi.sql.dictionary.TablePermsDescriptor;
+import org.apache.derby.iapi.sql.dictionary.ColPermsDescriptor;
+import org.apache.derby.iapi.sql.dictionary.RoutinePermsDescriptor;
+import org.apache.derby.iapi.sql.dictionary.PermissionsDescriptor;
 import org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor;
 import org.apache.derby.iapi.sql.dictionary.SPSDescriptor;
 import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
@@ -250,8 +256,6 @@
     protected boolean convertIdToLower;
     // Convert identifiers to lower case (as in Foundation) or not.
     
-	private	static final int		NUM_NONCORE = 12;
-
 	// This array of non-core table names *MUST* be in the same order
 	// as the non-core table numbers, above.
 	private static final String[] nonCoreNames = {
@@ -266,9 +270,15 @@
 									"SYSFILES",
 									"SYSTRIGGERS",
 									"SYSSTATISTICS",
-									"SYSDUMMY1"
+									"SYSDUMMY1",
+                                    "SYSTABLEPERMS",
+                                    "SYSCOLPERMS",
+                                    "SYSROUTINEPERMS",
+                                    "SYSREQUIREDPERM"
 									};
 
+	private	static final int		NUM_NONCORE = nonCoreNames.length;
+
     /**
      * List of all "system" schemas
      * <p>
@@ -333,6 +343,10 @@
 	int				tdCacheSize;
 	int				stmtCacheSize;	
 
+    /* Cache of permissions data */
+    CacheManager permissionsCache;
+    int permissionsCacheSize;
+
 	/*
 	** Lockable object for synchronizing transition from caching to non-caching
 	*/
@@ -524,6 +538,10 @@
 		stmtCacheSize = PropertyUtil.intPropertyValue(Property.LANG_SPS_CACHE_SIZE, value,
 									   0, Integer.MAX_VALUE, Property.LANG_SPS_CACHE_SIZE_DEFAULT);
 
+		value = startParams.getProperty(Property.LANG_PERMISSIONS_CACHE_SIZE);
+		permissionsCacheSize = PropertyUtil.intPropertyValue(Property.LANG_PERMISSIONS_CACHE_SIZE, value,
+									   0, Integer.MAX_VALUE, Property.LANG_PERMISSIONS_CACHE_SIZE_DEFAULT);
+
 
 		/*
 		 * data dictionary contexts are only associated with connections.
@@ -643,6 +661,27 @@
 		booting = false;
 	}
 
+    private CacheManager getPermissionsCache() throws StandardException
+    {
+        if( permissionsCache == null)
+        {
+            CacheFactory cf =
+              (CacheFactory) Monitor.startSystemModule(org.apache.derby.iapi.reference.Module.CacheFactory);
+            LanguageConnectionContext lcc = getLCC();
+            TransactionController tc = lcc.getTransactionExecute();
+            permissionsCacheSize = PropertyUtil.getServiceInt( tc,
+                                                               Property.LANG_PERMISSIONS_CACHE_SIZE,
+                                                               40, /* min value */
+                                                               Integer.MAX_VALUE,
+                                                               permissionsCacheSize /* value from boot time. */);
+            permissionsCache = cf.newCacheManager( this,
+                                                   "PermissionsCache",
+                                                   permissionsCacheSize,
+                                                   permissionsCacheSize);
+        }
+        return permissionsCache;
+    } // end of getPermissionsCache
+
 	/** 
 	 * sets the dependencymanager associated with this dd. subclasses can
 	 * override this to install their own funky dependency manager.
@@ -680,6 +719,8 @@
 			return new OIDTDCacheable(this);
 		else if (cm == nameTdCache)
 			return new NameTDCacheable(this);
+        else if( cm == permissionsCache)
+            return new PermissionsCacheable(this);
 		else {
 			return new SPSNameCacheable(this);
 		}
@@ -7551,6 +7592,26 @@
 				retval = new TabInfoImpl(new SYSDUMMY1RowFactory(
 												 luuidFactory, exFactory, dvf, convertIdToLower));					 
 				break;
+
+			  case SYSTABLEPERMS_CATALOG_NUM:
+				retval = new TabInfoImpl(new SYSTABLEPERMSRowFactory(
+												 luuidFactory, exFactory, dvf, convertIdToLower));					 
+				break;
+
+			  case SYSCOLPERMS_CATALOG_NUM:
+				retval = new TabInfoImpl(new SYSCOLPERMSRowFactory(
+												 luuidFactory, exFactory, dvf, convertIdToLower));					 
+				break;
+
+			  case SYSROUTINEPERMS_CATALOG_NUM:
+				retval = new TabInfoImpl(new SYSROUTINEPERMSRowFactory(
+												 luuidFactory, exFactory, dvf, convertIdToLower));					 
+				break;
+
+			  case SYSREQUIREDPERM_CATALOG_NUM:
+				retval = new TabInfoImpl(new SYSREQUIREDPERMRowFactory(
+												 luuidFactory, exFactory, dvf, convertIdToLower));					 
+				break;
 			}
 
 			initSystemIndexVariables(retval);
@@ -9526,6 +9587,273 @@
 		return java.util.Collections.synchronizedList(new java.util.LinkedList());
 	}
 
+    /**
+     * Get one user's privileges on a table
+     *
+     * @param tableUUID
+     * @param authorizationId The user name
+     *
+     * @return a TablePermsDescriptor or null if the user has no permissions on the table.
+     *
+     * @exception StandardException
+     */
+    public TablePermsDescriptor getTablePermissions( UUID tableUUID, String authorizationId)
+        throws StandardException
+    {
+        TablePermsDescriptor key = new TablePermsDescriptor( this, authorizationId, (String) null, tableUUID);
+        return (TablePermsDescriptor) getPermissions( key);
+    } // end of getTablePermissions
+
+    private Object getPermissions( PermissionsDescriptor key) throws StandardException
+    {
+        // RESOLVE get a READ COMMITTED (shared) lock on the permission row
+        Cacheable entry = getPermissionsCache().find( key);
+        if( entry == null)
+            return null;
+        Object perms = entry.getIdentity();
+        getPermissionsCache().release( entry);
+        return perms;
+    }
+
+    /**
+     * Get one user's column privileges for a table.
+     *
+     * @param tableUUID
+     * @param privType Authorizer.SELECT_PRIV, Authorizer.UPDATE_PRIV, or Authorizer.REFERENCES_PRIV
+     * @param forGrant
+     * @param authorizationId The user name
+     *
+     * @return a ColPermsDescriptor or null if the user has no separate column
+     *         permissions of the specified type on the table. Note that the user may have been granted
+     *         permission on all the columns of the table (no column list), in which case this routine
+     *         will return null. You must also call getTablePermissions to see if the user has permission
+     *         on a set of columns.
+     *
+     * @exception StandardException
+     */
+    public ColPermsDescriptor getColumnPermissions( UUID tableUUID,
+                                                    int privType,
+                                                    boolean forGrant,
+                                                    String authorizationId)
+        throws StandardException
+    {
+        String privTypeStr = forGrant ? colPrivTypeMapForGrant[privType] : colPrivTypeMap[privType];
+        if( SanityManager.DEBUG)
+            SanityManager.ASSERT( privTypeStr != null,
+                                  "Invalid column privilege type: " + privType);
+        ColPermsDescriptor key = new ColPermsDescriptor( this,
+                                                         authorizationId,
+                                                         (String) null,
+                                                         tableUUID,
+                                                         privTypeStr);
+        return (ColPermsDescriptor) getPermissions( key);
+    } // end of getColumnPermissions
+
+    private static final String[] colPrivTypeMap;
+    private static final String[] colPrivTypeMapForGrant;
+    static {
+        colPrivTypeMap = new String[ Authorizer.PRIV_TYPE_COUNT];
+        colPrivTypeMapForGrant = new String[ Authorizer.PRIV_TYPE_COUNT];
+        colPrivTypeMap[ Authorizer.SELECT_PRIV] = "s";
+        colPrivTypeMapForGrant[ Authorizer.SELECT_PRIV] = "S";
+        colPrivTypeMap[ Authorizer.UPDATE_PRIV] = "u";
+        colPrivTypeMapForGrant[ Authorizer.UPDATE_PRIV] = "U";
+        colPrivTypeMap[ Authorizer.REFERENCES_PRIV] = "r";
+        colPrivTypeMapForGrant[ Authorizer.REFERENCES_PRIV] = "R";
+    }
+    
+    /**
+     * Get one user's permissions for a routine (function or procedure).
+     *
+     * @param routineUUID
+     * @param authorizationId The user's name
+     *
+     * @return The descriptor of the users permissions for the routine.
+     *
+     * @exception StandardException
+     */
+    public RoutinePermsDescriptor getRoutinePermissions( UUID routineUUID, String authorizationId)
+        throws StandardException
+    {
+        RoutinePermsDescriptor key = new RoutinePermsDescriptor( this, authorizationId, (String) null);
+
+        return (RoutinePermsDescriptor) getPermissions( key);
+    } // end of getRoutinePermissions
+
+    /**
+     * Add or remove a permission to/from the permission database.
+     *
+     * @param add if true then the permission is added, if false the permission is removed
+     * @param perm
+     * @param grantee
+     * @param tc
+     *
+     */
+    public void addRemovePermissionsDescriptor( boolean add,
+                                                PermissionsDescriptor perm,
+                                                String grantee,
+                                                TransactionController tc)
+        throws StandardException
+    {
+        int catalogNumber = perm.getCatalogNumber();
+
+        perm.setGrantee( grantee);
+        TabInfo ti = getNonCoreTI( catalogNumber);
+        PermissionsCatalogRowFactory rf = (PermissionsCatalogRowFactory) ti.getCatalogRowFactory();
+        int primaryIndexNumber = rf.getPrimaryIndexNumber();
+        ConglomerateController heapCC = tc.openConglomerate( ti.getHeapConglomerate(),
+                                                             false,  // do not keep open across commits
+                                                             0,
+                                                             TransactionController.MODE_RECORD,
+                                                             TransactionController.ISOLATION_REPEATABLE_READ);
+        RowLocation rl = null;
+        try
+        {
+            rl = heapCC.newRowLocationTemplate();
+        }
+        finally
+        {
+            heapCC.close();
+            heapCC = null;
+        }
+        ExecIndexRow key = rf.buildIndexKeyRow( primaryIndexNumber, perm);
+        ExecRow existingRow = ti.getRow( tc, key, primaryIndexNumber);
+        if( existingRow == null)
+        {
+            if( ! add)
+                return;
+            ExecRow row = ti.getCatalogRowFactory().makeRow( perm, (TupleDescriptor) null);
+            int insertRetCode = ti.insertRow(row, tc, true /* wait */);
+            if( SanityManager.DEBUG)
+                SanityManager.ASSERT( insertRetCode == TabInfo.ROWNOTDUPLICATE,
+                                      "Race condition in inserting table privilege.");
+        }
+        else
+        {
+            // add/remove these permissions to/from the existing permissions
+            boolean[] colsChanged = new boolean[ existingRow.nColumns()];
+            boolean[] indicesToUpdate = new boolean[ rf.getNumIndexes()];
+            int changedColCount = 0;
+            if( add)
+                changedColCount = rf.orPermissions( existingRow, perm, colsChanged);
+            else
+                changedColCount = rf.removePermissions( existingRow, perm, colsChanged);
+            if( changedColCount == 0)
+                return;
+            if( changedColCount < 0)
+            {
+                // No permissions left in the current row
+                ti.deleteRow( tc, key, primaryIndexNumber);
+            }
+            else if( changedColCount > 0)
+            {
+                int[] colsToUpdate = new int[changedColCount];
+                changedColCount = 0;
+                for( int i = 0; i < colsChanged.length; i++)
+                {
+                    if( colsChanged[i])
+                        colsToUpdate[ changedColCount++] = i + 1;
+                }
+                if( SanityManager.DEBUG)
+                    SanityManager.ASSERT(
+                        changedColCount == colsToUpdate.length,
+                        "return value of " + rf.getClass().getName() +
+                        ".orPermissions does not match the number of booleans it set in colsChanged.");
+                ti.updateRow( key, existingRow, primaryIndexNumber, indicesToUpdate, colsToUpdate, tc, true /* wait */);
+            }
+        }
+        // Remove cached permissions data. The cache may hold permissions data for this key even if
+        // the row in the permissions table is new. In that case the cache may have an entry indicating no
+        // permissions
+        Cacheable cacheEntry = getPermissionsCache().findCached( perm);
+        if( cacheEntry != null)
+            getPermissionsCache().remove( cacheEntry);
+    } // end of addPermissionsDescriptor
+
+    /**
+     * Get a table permissions descriptor from the system tables, without going through the cache.
+     * This method is called to fill the permissions cache.
+     *
+     * @param grantee
+     * @param tableUUID
+     *
+     * @returns a TablePermsDescriptor that describes the table permissions granted to the grantee, null
+     *          if no table-level permissions have been granted to him on the table.
+     *
+     * @exception StandardException
+     */
+    TablePermsDescriptor getUncachedTablePermsDescriptor( TablePermsDescriptor key)
+        throws StandardException
+    {
+        return (TablePermsDescriptor)
+          getUncachedPermissionsDescriptor( SYSTABLEPERMS_CATALOG_NUM,
+                                            SYSTABLEPERMSRowFactory.GRANTEE_TABLE_GRANTOR_INDEX_NUM,
+                                            key);
+    } // end of getUncachedTablePermsDescriptor
+
+
+    /**
+     * Get a column permissions descriptor from the system tables, without going through the cache.
+     * This method is called to fill the permissions cache.
+     *
+     * @param grantee
+     * @param tableUUID
+     * @param privType "s", "u", "r", "S", "U", or "R"
+     *
+     * @returns a ColPermsDescriptor that describes the column permissions granted to the grantee, null
+     *          if no column permissions have been granted to him on the table.
+     *
+     * @exception StandardException
+     */
+    ColPermsDescriptor getUncachedColPermsDescriptor( ColPermsDescriptor key)
+        throws StandardException
+    {
+        return (ColPermsDescriptor)
+          getUncachedPermissionsDescriptor( SYSCOLPERMS_CATALOG_NUM,
+                                            SYSCOLPERMSRowFactory.GRANTEE_TABLE_TYPE_GRANTOR_INDEX_NUM,
+                                            key);
+                                                                        
+    } // end of getUncachedColPermsDescriptor
+
+    private TupleDescriptor getUncachedPermissionsDescriptor( int catalogNumber,
+                                                              int indexNumber,
+                                                              PermissionsDescriptor key)
+        throws StandardException
+    {
+		TabInfo ti = getNonCoreTI( catalogNumber);
+        PermissionsCatalogRowFactory rowFactory = (PermissionsCatalogRowFactory) ti.getCatalogRowFactory();
+        ExecIndexRow keyRow = rowFactory.buildIndexKeyRow( indexNumber, key);
+        return
+          getDescriptorViaIndex( indexNumber,
+                                 keyRow,
+                                 (ScanQualifier [][]) null,
+                                 ti,
+                                 (TupleDescriptor) null,
+                                 (List) null,
+                                 false);
+    } // end of getUncachedPermissionsDescriptor
+
+    /**
+     * Get a routine permissions descriptor from the system tables, without going through the cache.
+     * This method is called to fill the permissions cache.
+     *
+     * @param grantee
+     * @param routineUUID
+     *
+     * @returns a RoutinePermsDescriptor that describes the table permissions granted to the grantee, null
+     *          if no table-level permissions have been granted to him on the table.
+     *
+     * @exception StandardException
+     */
+    RoutinePermsDescriptor getUncachedRoutinePermsDescriptor( RoutinePermsDescriptor key)
+        throws StandardException
+    {
+        return (RoutinePermsDescriptor)
+          getUncachedPermissionsDescriptor( SYSROUTINEPERMS_CATALOG_NUM,
+                                            SYSROUTINEPERMSRowFactory.GRANTEE_ALIAS_GRANTOR_INDEX_NUM,
+                                            key);
+    } // end of getUncachedRoutinePermsDescriptor
+ 
 	private String[][] DIAG_VTI_CLASSES =
 	{
 			{"LOCK_TABLE", "org.apache.derby.diag.LockTable"},



Mime
View raw message